问:
Executing user configuration settings
For an API I'm building what it does is load an XML file that is passed to it as a string, drill to the correct element, modify values, and return the modified XML.

I'm doing something like this in my code

```<code>if (valid)
{
    XDocument docRoot = XDocument.Parse(XMLstring);

    var node1 = docRoot.Descendants(namespace + @"node1");

    foreach (var result in node1)
    {
        var child1 = result.Descendants(ns + "child1");

        var test = child1.First();
        test.SetValue(Transform(test.Value));
    }

    //return the transformed XML

}
else { }
</code>```

Now I want to create a configuration file in XML format that allows user to specify which nodes in the XML to modify and what modification to perform, (later I want to make use of this in a GUI)

so something like

```<code><root Value="">
    <Modify Xpath="\parent\child1\superchild\" Attribute="" Mode="delete" />
    <Modify Xpath="\parent\child2\" Attribute="Value" Mode="multiply" />
</root>
</code>```

And I have these two pieces but don't know how to connect them together.  I think I  have to make a class from my XML configuration file and somehow map those to the values in the other XML.

答:
I have created a possible solution by leveraging the standard configuration classes from .Net and some common patterns to achieve what you want.

Based on your sample XML and configuration I assume you want to perform on action (Mode) on element (Xpath) or an attribute (Attribute) on a given xml.

To make this possible I created an Interface that takes the element and the attribute to perform one single action. This can be implemented with a command pattern.

The correct implementation class is selected by using a factory pattern. By providing a Register method you enable users of your api to provide implementation of actions you didn't provide. You only share an common interface and the Factory class. The rest of the implementation is hidden.

Do notice that in this example there is only one instance of each command that is reused. If you require a per call instance the factory needs to be extended and would require concretetypes to be registered.

The main program would look this:

```<code>static void Main()
{
    // get the config
    var root = (Root) ConfigurationManager.GetSection("root");

    // your input xml
    var docRoot = XDocument.Parse(@"<parent><child1><superchild></superchild></child1><child2 Value=""3""></child2></parent>");

    // loop over all actions that need to be performed
    foreach (ModifyElement modact in root.ModifyActions)
    {
        var nodes = docRoot.XPathSelectElements(modact.Xpath);

        // create the correct command class based on the value of Mode
        var cmd = ModifyCommandFactory.GetInstance(modact.Mode);

        foreach (var node in nodes)
        {
            // if we have an attribute, try to grab it
            XAttribute attr = String.IsNullOrEmpty(modact.Attribute)?
               null:node.Attributes(modact.Attribute).SingleOrDefault();
            // now execute our command
            cmd.Execute(node, attr);
        }
    }

    var sb = new StringBuilder();
    var sw = new XmlTextWriter(new StringWriter(sb));
    docRoot.WriteTo(sw);
    sw.Close();
    Debug.WriteLine(sb);
}
</code>```

The slightly adapted app.config file to hold your Modify commands

```<code><configuration>

  <configSections>
    <section name="root" type="WindowsFormsApplication1.Root, WindowsFormsApplication1"/>
  </configSections>

  <root Value="">
    <actions>
        <Modify Xpath="/parent/child1/superchild" Attribute="" Mode="delete" />
        <Modify Xpath="/parent/child2" Attribute="Value" Mode="multiply" />
    </actions>
  </root>

</configuration>
</code>```

To read your config values a pretty basic implementation of the configuration classes is needed for the ConfigSection, ConfigCollection and ConfigElement. You find the code needed at the end of this post.

Interface

The common interface has an Execite method that takes an XElement and an XAttribute

```<code>public interface IModifyCommand
{
    void Execute(XElement element, XAttribute attribute);
}
</code>```

Commands

For each mode we implement a ConcreteCommand that implements IModifyCommand

Multiply

```<code>public class Multiply:IModifyCommand
{
    public void Execute(XElement element, XAttribute attribute)
    {
        int value;
        if (attribute != null &&
            Int32.TryParse(attribute.Value, out value))
        {
            // this can break due to oveflow!
            value *= value;
            attribute.Value = value.ToString(CultureInfo.InvariantCulture);
        }
        if (element != null &&
            Int32.TryParse(element.Value, out value))
        {
            // this can break due to oveflow!
            value *= value;
            element.Value = value.ToString(CultureInfo.InvariantCulture);
        }

    }
}
</code>```

DeleteCommand

```<code>public class Delete:IModifyCommand
{
    public void Execute(XElement element, XAttribute attribute)
    {
        if (attribute != null)
        {
            attribute.Remove();
        }
        if (element != null)
        {
            element.Remove();
        }
    }
}
</code>```

NoopCommand

To make our life easier we also have a NoopCommand for the case when no suitable Mode is defined in the config.

```<code>public class Noop:IModifyCommand
{
    public void Execute(XElement element, XAttribute attribute)
    {
        // do nothing
    }
}
</code>```

Factory to provide instances for several modes

```<code>public static class ModifyCommandFactory
{
    static readonly Dictionary<string,IModifyCommand> commands = new Dictionary<string, IModifyCommand>();
    static ModifyCommandFactory()
    {
        // our well known commands
        Register("delete", new Delete());
        Register("multiply", new Multiply());
    }

    internal static IModifyCommand GetInstance(string key)
    {
        IModifyCommand cmd;
        if (!commands.TryGetValue(key, out cmd))
        {
            cmd = new Noop(); // nothing found, so use the No-operation command
        }
        return cmd;
     }

     // will be used by users to provide their own commands
     public static void Register(string mode, IModifyCommand modifycommand)
     {
         commands.Add(mode, modifycommand);
     }
}
</code>```

ConfigSection

```<code>public class Root:ConfigurationSection
{
    private const string ValueKey = "Value";
    private const string ActionsKey = "actions";

    [ConfigurationProperty(ValueKey,
         IsRequired = true,
         IsKey = false)]
    public string Value
    {
        get { return (string)this[ValueKey];}
        set { this[ValueKey] = value; }
    }

    [ConfigurationProperty(ActionsKey,
        IsRequired = true,
        IsKey = false)]
    public ModifyCollection ModifyActions
    {
        get { return (ModifyCollection)this[ActionsKey]; }
        set { this[ActionsKey] = value; }
    }
}
</code>```

ConfigCollection

```<code>public class ModifyCollection:ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new ModifyElement();
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get{ return ConfigurationElementCollectionType.BasicMap;}
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        var me = (ModifyElement) element;
        return me.Xpath + me.Attribute + me.Mode;
    }

    protected override string ElementName
    {
        get { return "Modify"; }
    }
}
</code>```

ConfigElement

```<code>public class ModifyElement:ConfigurationElement
{
    private const string XPathKey = "Xpath";
    private const string AttributeKey = "Attribute";
    private const string ModeKey = "Mode";

    [ConfigurationProperty(XPathKey,
         IsRequired = true,
         IsKey = false)]
    public string Xpath
    {
        get { return (string)this[XPathKey]; }
        set { this[XPathKey] = value; }
    }

    [ConfigurationProperty(AttributeKey,
         IsRequired = true,
         IsKey = false)]
    public string Attribute
    {
        get { return (string)this[AttributeKey]; }
        set { this[AttributeKey] = value; }
    }

    [ConfigurationProperty(ModeKey,
         IsRequired = true,
         IsKey = false)]
    public string Mode
    {
        get { return (string)this[ModeKey]; }
        set { this[ModeKey] = value; }
    }
}
</code>```

Title: Executing user configuration settings

Body:
I have created a possible solution by leveraging the standard configuration classes from .Net and some common patterns to achieve what you want.

Based on your sample XML and configuration I assume you want to perform on action (Mode) on element (Xpath) or an attribute (Attribute) on a given xml.

To make this possible I created an Interface that takes the element and the attribute to perform one single action. This can be implemented with a command pattern.

The correct implementation class is selected by using a factory pattern. By providing a Register method you enable users of your api to provide implementation of actions you didn't provide. You only share an common interface and the Factory class. The rest of the implementation is hidden.

Do notice that in this example there is only one instance of each command that is reused. If you require a per call instance the factory needs to be extended and would require concretetypes to be registered.

The main program would look this:

static void Main()
{
    // get the config
    var root = (Root) ConfigurationManager.GetSection("root");

    // your input xml
    var docRoot = XDocument.Parse(@"<parent><child1><superchild></superchild></child1><child2 Value=""3""></child2></parent>");

    // loop over all actions that need to be performed
    foreach (ModifyElement modact in root.ModifyActions)
    {
        var nodes = docRoot.XPathSelectElements(modact.Xpath);

        // create the correct command class based on the value of Mode
        var cmd = ModifyCommandFactory.GetInstance(modact.Mode);

        foreach (var node in nodes)
        {
            // if we have an attribute, try to grab it
            XAttribute attr = String.IsNullOrEmpty(modact.Attribute)?
               null:node.Attributes(modact.Attribute).SingleOrDefault();
            // now execute our command
            cmd.Execute(node, attr);
        }
    }

    var sb = new StringBuilder();
    var sw = new XmlTextWriter(new StringWriter(sb));
    docRoot.WriteTo(sw);
    sw.Close();
    Debug.WriteLine(sb);
}

The slightly adapted app.config file to hold your Modify commands

<configuration>

  <configSections>
    <section name="root" type="WindowsFormsApplication1.Root, WindowsFormsApplication1"/>
  </configSections>

  <root Value="">
    <actions>
        <Modify Xpath="/parent/child1/superchild" Attribute="" Mode="delete" />
        <Modify Xpath="/parent/child2" Attribute="Value" Mode="multiply" />
    </actions>
  </root>

</configuration>

To read your config values a pretty basic implementation of the configuration classes is needed for the ConfigSection, ConfigCollection and ConfigElement. You find the code needed at the end of this post.

Interface

The common interface has an Execite method that takes an XElement and an XAttribute

public interface IModifyCommand
{
    void Execute(XElement element, XAttribute attribute);
}

Commands

For each mode we implement a ConcreteCommand that implements IModifyCommand

Multiply

public class Multiply:IModifyCommand
{
    public void Execute(XElement element, XAttribute attribute)
    {
        int value;
        if (attribute != null &&
            Int32.TryParse(attribute.Value, out value))
        {
            // this can break due to oveflow!
            value *= value;
            attribute.Value = value.ToString(CultureInfo.InvariantCulture);
        }
        if (element != null &&
            Int32.TryParse(element.Value, out value))
        {
            // this can break due to oveflow!
            value *= value;
            element.Value = value.ToString(CultureInfo.InvariantCulture);
        }

    }
}

DeleteCommand

public class Delete:IModifyCommand
{
    public void Execute(XElement element, XAttribute attribute)
    {
        if (attribute != null)
        {
            attribute.Remove();
        }
        if (element != null)
        {
            element.Remove();
        }
    }
}

NoopCommand

To make our life easier we also have a NoopCommand for the case when no suitable Mode is defined in the config.

public class Noop:IModifyCommand
{
    public void Execute(XElement element, XAttribute attribute)
    {
        // do nothing
    }
}

Factory to provide instances for several modes

public static class ModifyCommandFactory
{
    static readonly Dictionary<string,IModifyCommand> commands = new Dictionary<string, IModifyCommand>();
    static ModifyCommandFactory()
    {
        // our well known commands
        Register("delete", new Delete());
        Register("multiply", new Multiply());
    }

    internal static IModifyCommand GetInstance(string key)
    {
        IModifyCommand cmd;
        if (!commands.TryGetValue(key, out cmd))
        {
            cmd = new Noop(); // nothing found, so use the No-operation command
        }
        return cmd;
     }

     // will be used by users to provide their own commands
     public static void Register(string mode, IModifyCommand modifycommand)
     {
         commands.Add(mode, modifycommand);
     }
}

ConfigSection

public class Root:ConfigurationSection
{
    private const string ValueKey = "Value";
    private const string ActionsKey = "actions";

    [ConfigurationProperty(ValueKey,
         IsRequired = true,
         IsKey = false)]
    public string Value
    {
        get { return (string)this[ValueKey];}
        set { this[ValueKey] = value; }
    }

    [ConfigurationProperty(ActionsKey,
        IsRequired = true,
        IsKey = false)]
    public ModifyCollection ModifyActions
    {
        get { return (ModifyCollection)this[ActionsKey]; }
        set { this[ActionsKey] = value; }
    }
}

ConfigCollection

public class ModifyCollection:ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new ModifyElement();
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get{ return ConfigurationElementCollectionType.BasicMap;}
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        var me = (ModifyElement) element;
        return me.Xpath + me.Attribute + me.Mode;
    }

    protected override string ElementName
    {
        get { return "Modify"; }
    }
}

ConfigElement

public class ModifyElement:ConfigurationElement
{
    private const string XPathKey = "Xpath";
    private const string AttributeKey = "Attribute";
    private const string ModeKey = "Mode";

    [ConfigurationProperty(XPathKey,
         IsRequired = true,
         IsKey = false)]
    public string Xpath
    {
        get { return (string)this[XPathKey]; }
        set { this[XPathKey] = value; }
    }

    [ConfigurationProperty(AttributeKey,
         IsRequired = true,
         IsKey = false)]
    public string Attribute
    {
        get { return (string)this[AttributeKey]; }
        set { this[AttributeKey] = value; }
    }

    [ConfigurationProperty(ModeKey,
         IsRequired = true,
         IsKey = false)]
    public string Mode
    {
        get { return (string)this[ModeKey]; }
        set { this[ModeKey] = value; }
    }
}


问:
What is the exact meaning of Platform independence?
What is the meaning of platform independence?

I am taking the case of Java. Can I run a Java application on Linux that built on Windows platform? Or the reverse?

Can I use a same (or exact) programming algorithm on both operating systems?

In my view File Types are platform independent like Videos, Images, Documents etc.

答:
Since the JVM requires a host, I can tell you that a Java program is not platform independent. Also, the Java language by design has requirements on the filesystem resulting in short class names if the system is using a FAT16 partition:

```<code>class FOOBAR
</code>```

is the same as

```<code>class Foobar
</code>```

and the name

```<code>class AbstractPrinterFactory
</code>```

is impossible.

As comparison, C has very little runtime requirements and can therefore offer higher portability. It is still possible to backport smaller C programs to really low-end devices.

ContentLicense: CC BY-SA 3.0

Body:
Since the JVM requires a host, I can tell you that a Java program is not platform independent. Also, the Java language by design has requirements on the filesystem resulting in short class names if the system is using a FAT16 partition:

class FOOBAR

is the same as

class Foobar

and the name

class AbstractPrinterFactory

is impossible.

As comparison, C has very little runtime requirements and can therefore offer higher portability. It is still possible to backport smaller C programs to really low-end devices.


问:
Managing resource paths in source code
I suspect this is something that many of you have dealt with, and I'm certain there's articles on how to do it, but I can't seem to find them.

My problem is that my various constant classes in Java (read: classes containing lists of static constant values) are too many and too big, and some of them have some annoying complex static initializers.

We've got a file paths class, a file name class, a constants class, a strings class, a colors class (for the swing components) and a bunch of css for the JavaFX components... it goes on and on. The CSS is manageable, the rest of it is quickly becoming not-so.

Having classes like this:

```<code>public class Constants {
    public static final String something = "Something";
    public static final Path someResourcePath = staticMethodCall(RootString, dirTraversal);
    public static final Image spinner = iconFindingStaticMethod(dirTraversal)
    //and on and on for hundreds (not yet thousands thankfully) of lines

    //and then often we have
    static{
        //code that determines our environment and fudges some paths as appropriate
        //sometimes we ask the class loader to find some things for us
        //nothing too scary, but still, static initializers are never friendly.
    }
}
</code>```

is good for one very powerful reason: Every java programmer out there knows exactly what this class does and how it works. The ones with static initializers might be a little confusing, but for the most part, the above is PO-Static-JO. I like that.

But it also introduces a number of problems. I'll try to enumerate the ones I know of here:

the most obvious code smell of all: these classes are multiplying and they're all annoyingly large. We've got one for file extensions thats got a couple dozen entries, including things like public static final String XMLFileExtension = "xml". That might be a bit much, but I'm not really willing to fault the dev who wrote it. It wouldn't be hard to replace references to that with the string value, but I'd like to encourage this kind of code, so I'd feel stupid doing it. But these classes are getting large and annoying.

use of static constants is not testable. This in itself isn't too often a problem since the values in those classes are supposed to be simple, but it does turn into a problem when you do something like Constants.someFilePath.exists() ? a() : b() (since there's no way to intercept that exists() call, from any environment we're going to ask the actual file system if that path exists, which is a problem for testing.) We're on guice, so I'd really like to inject these values like everything else, so they can be modified by our fixtures with fake/stub/mock values.

It also introduces a dependency problem. Right now we have a couple of IntelliJ & Guice Modules (semi-separate code bases) under the same git repo. They all use our original module's constant files, which means all modules have a dependency with that module, but with static constants whats the solution? Copy-paste?

Some solutions I've thought of:

we could leverage guice and simply inject every single needed constant with an @Named parameter. This addresses problems 2 & 3, but compounds problem 1 since the binding logic would have to either be incredibly long and contain a huge swath of duplicate registration, or employ some pretty complex composition.

we could go the auto-generate-source-java-from-XML-or-JSON route, which I've used with Android and I believe some C# component I worked on briefly. The extra step in the build process adds a level of complexity in an area (that is: devops) that not a lot of developers are familiar with. It was nice to have just a big table in eclipse containing all my values, but the added complexity to the build process is unwanted. Furthermore the static initializer logic couldn't fit into this model.

stay the course with Java, maybe extract a package near the route called "Environment" or "constants", and then give that package a number of constant classes that can inherit other classes with shared fields. Regarding testability, we run into java inlining final fields. We could replace each field with a simple getter, but that makes an already overly verbose problem more verbose.

I really don't know how I want to tackle this. I've been telling myself to let it become a problem for a few months now, thinking that some kind of solution would emerge. It hasn't, and know we have a kind've gnarly dependency graph, hacks around testing code with file paths, and large constant classes.

What kind of solutions have you employed for managing these files? Am I being overly concerned and what we've got now is the best solution?

答:
If you have big static initialisers, you're probably not so much defining constants as caching calculated values that will persist over the lifetime of your application.

You may have better luck abstracting on functionality rather than values.  See if you can identify patterns in which you use these many constants, and pull these uses out into methods, and put these methods into interfaces.  Access your constants through methods as well.

Java example:

```<code>interface Platform {
    Image getSpinnerImage();
    // ...
}

// could be a caching proxy
class LocalPlatform implements Platform {
    private Image spinnerImage;
    public Image getSpinnerImage() {
        if ( spinnerImage == null ) {
            spinnerImage = loadSpinnerImage();
        }
        return spinnerImage;
    }
}
</code>```

This is both testable as injectable, and should take care of large static initialisers.

That's not to say that you should do away with all constants; do keep constants that are just that.  Having getXmlFileExtension() is crazy because any other implementation than return "xml" violates the principle of least surprise, but something like getDefaultInstallationPath() is a better candidate.

Given sufficient of these interfaces, you're going to progress to what you've already started to experience: a sort of platform project on which many of your other parts will depend.  This is okay; just like Java has java.lang, you're going to have your environment/platform.

I've used this technique to some success in large projects that had similar issues to what you described.  It did not drastically reduce the lines of code, but it did encapsulate that code, make it easier to debug and verify, and ended up simplifying much of the rest of the project.

Note: If you feel some parts of your code are problematic, you can always try presenting your actual code to the people on Code Review.

Title: Managing resource paths in source code

Body:
If you have big static initialisers, you're probably not so much defining constants as caching calculated values that will persist over the lifetime of your application.

You may have better luck abstracting on functionality rather than values.  See if you can identify patterns in which you use these many constants, and pull these uses out into methods, and put these methods into interfaces.  Access your constants through methods as well.

Java example:

interface Platform {
    Image getSpinnerImage();
    // ...
}

// could be a caching proxy
class LocalPlatform implements Platform {
    private Image spinnerImage;
    public Image getSpinnerImage() {
        if ( spinnerImage == null ) {
            spinnerImage = loadSpinnerImage();
        }
        return spinnerImage;
    }
}

This is both testable as injectable, and should take care of large static initialisers.

That's not to say that you should do away with all constants; do keep constants that are just that.  Having getXmlFileExtension() is crazy because any other implementation than return "xml" violates the principle of least surprise, but something like getDefaultInstallationPath() is a better candidate.

Given sufficient of these interfaces, you're going to progress to what you've already started to experience: a sort of platform project on which many of your other parts will depend.  This is okay; just like Java has java.lang, you're going to have your environment/platform.

I've used this technique to some success in large projects that had similar issues to what you described.  It did not drastically reduce the lines of code, but it did encapsulate that code, make it easier to debug and verify, and ended up simplifying much of the rest of the project.

Note: If you feel some parts of your code are problematic, you can always try presenting your actual code to the people on Code Review.


问:
Only functions without a class in cpp file! good design or not?
When I was going through the project on which I am working, I came across a cpp file, which has only functions and static variables.I was wondering why they have not put everything into a class! Whenever the inside functions have to be called, the cpp file is included.

Is this a good design? what are the pros and cons of these type of design?

for ex.

```<code>//independent.cpp
#include "someclass.h"
static int var1;
static someclass object("hello");
static bool var2;

void foo(const char* dir, const char* filename){
...
}

somefile.cpp
#include "independent.cpp"
class sample{
public:
  void caller(){
  foo("c:\", "file.txt");
  }
}
</code>```

答:
One of the driving reasons why to not implement a set of utility functions as a class is th fact that when it comes to having a class with no state which only provides functions, then there's very little sense in instantiating that class as all of the instances are identical. There's no meaning in defining such a data type because data types are contracts about what the data/state represents. When there is no state or data, there's nothing to represent.

Many times it is not that straightforward though. For the sake of example (this is something you'd perhaps want in an actual self-contained class instead), consider a situation where you have a get_time_delta() function and want to return time spent since the last invocation of the get_time_delta() function -- a common situation when calculating for example how long it takes to run a render_scene() function in a game. You'd need to store the time for the first invocation and the time for the second invocation and subtract the first from the second -- but without state this is impossible. One way to do this would be to implement a class and hold this state as private member variables, but if this is a generic utility class, that timing data which is relevant for get_time_delta() only gets exposed to other utility functions too. This is bad because minimizing the scope of the variables is desired. One good way to go about this is to have the internal timing data local to the get_time_delta() function by specifying it with static storage-class specifiers.

As it stands, in the aforementioned example we do not need state for the class. So why do we need a class to begin with? Say we have an API like this:

```<code>unsigned int delta_time = Util::get_time_delta();
</code>```

It would be unreasonable to need to instantiate Util as it holds no state. So either we declare get_time_delta() as static functions of the class or we declare get_time_delta() inside a namespace Util.

This all said, "the C++ way"(whatever it means, don't read to it too much) is to define utility functions within a namespace instead of as static member functions of an utility class.

In other languages, namely in C# and Java, there's a pattern called utility pattern which simulates namespaces -- placing utility functions behind a "namespace" by declaring them as static member functions of a class. In C++ this is not needed at all because of built-in namespaces and free-standing functions.

Body:
One of the driving reasons why to not implement a set of utility functions as a class is th fact that when it comes to having a class with no state which only provides functions, then there's very little sense in instantiating that class as all of the instances are identical. There's no meaning in defining such a data type because data types are contracts about what the data/state represents. When there is no state or data, there's nothing to represent.

Many times it is not that straightforward though. For the sake of example (this is something you'd perhaps want in an actual self-contained class instead), consider a situation where you have a get_time_delta() function and want to return time spent since the last invocation of the get_time_delta() function -- a common situation when calculating for example how long it takes to run a render_scene() function in a game. You'd need to store the time for the first invocation and the time for the second invocation and subtract the first from the second -- but without state this is impossible. One way to do this would be to implement a class and hold this state as private member variables, but if this is a generic utility class, that timing data which is relevant for get_time_delta() only gets exposed to other utility functions too. This is bad because minimizing the scope of the variables is desired. One good way to go about this is to have the internal timing data local to the get_time_delta() function by specifying it with static storage-class specifiers.

As it stands, in the aforementioned example we do not need state for the class. So why do we need a class to begin with? Say we have an API like this:

unsigned int delta_time = Util::get_time_delta();

It would be unreasonable to need to instantiate Util as it holds no state. So either we declare get_time_delta() as static functions of the class or we declare get_time_delta() inside a namespace Util.

This all said, "the C++ way"(whatever it means, don't read to it too much) is to define utility functions within a namespace instead of as static member functions of an utility class.

In other languages, namely in C# and Java, there's a pattern called utility pattern which simulates namespaces -- placing utility functions behind a "namespace" by declaring them as static member functions of a class. In C++ this is not needed at all because of built-in namespaces and free-standing functions.


问:
I am making 4-5x more story points than average, but producing bugs at half the rate. Graphs say it's 2x more bugs, how to deal with that?
So it is generally accepted that top tier programmers can produce an order of magnitude more/better code than their more average peers.

It's also generally accepted that the rate of errors made in code is relatively constant for programmers.

Instead, it tends to be impacted by the processes used when writing the code and after the code is written. (As I understand it) Humans tend to make mistakes at a fairly constant rate - better programmers just notice more of them and are quicker to fix them.

Note that both of above assertions come from Code Complete by Steve McConnell - so it's not a matter of differing perspectives.

So I've started to see this recently in my code. I can hammer out about 4-5x the amount of code as many of my peers (measured by story points estimated by the team), with higher quality (based on performance metrics and number of changes made after check-in). But I still make mistakes. Between better unit tests, a better understanding of what the code is doing, and a better eye for issues when doing code reviews I'm not producing 4-5x the number of bugs.

But I'm still producing about twice as many bugs found by QA as other developers on my team. As you might imagine, this causes some problems with non-technical folks doing metric measurements (read: my boss).

I've tried to point out that I'm producing bugs at half the rate of my peers (and fix twice as many), but it's a hard sell when there's graphs saying I produce twice as many bugs.

So, how to deal with the fact that increased productivity will lead to an increased number of bugs?

答:
Trying to enlighten management is a non-starter. There's an old cliché, "Are you going to believe me or your lying eyes?" What concerns your bosses are the bug counts. No amount of rationalization will tell them it's acceptable. It's more than twice as risky. In addition, you're not the only one affected by your bug count. QA has twice the work trying to identify your bugs, so management is going to want you to make less of them.

The best solution is to reduce the number of bugs you produce, period. Not only will management be happier, but you will be too. Won't you? Cause I'm pretty sure as much as you enjoy boasting you outperform your coworkers by a factor of four, you'd love to say you do it making the same number of, or even less, bugs than they do.

As you stated, "…the rate of errors made in code…tends to be impacted by the processes used when writing the code and after the code is written." If you want to alter the rate at which you produce bugs you're going to have to change the processes you use to write code.

Programmers use production methods to produce code, much as an assembly line uses methods to produce some mass-produced object. Okay, the software industry's practices are more like whittling knick-knacks from branches found in the woods. But since we're producing machines, we should employ the same rigor and discipline used for the high-speed machines of mass-production.

That includes the same techniques used in mass-production to reduce the defect rate: root-cause analysis to determine why bugs are made, and change the process so they aren't. Or at least that you catch before QA does.

Make up a list of your bugs. You've probably already got one thanks to the QA guys. Possibly categorized too. Type of bug, severity, the point at which the bug was injected into the code, etc.

Pick the largest category of bugs. Since your volume is so high, you should target that category first. Other categories include the ones easiest to find, and the ones easiest to make.

Knowing where those bugs are introduced into the code, look into making changes at that phase (and earlier) that prevents those bugs from happening, and ways to make catching them easier at that phase.

Be sure to look at non-programming related incidentals as well as they may make a difference in the quality of your work. Background music, interruptions, mealtimes, working too long without a break, hunger, etc.

What you find may lead you to go slower. On the other hand, it may help you produce even faster as you'll have less need to rework stuff you've already put behind you. As it is, four times as much code isn't close to being an order of magnitude better than your coworkers, so changing your process is most definitely the way to go.


答:
My guess is that it is used to make a bunch of "single purpose executables".

(Disclaimer: my C++ knowledge is not as good as the other answerers - my answer is just a guess.)

Observe that

This approach allows multiple reusable classes, "someclass.h", etc, to be included. So, one could deduce that the family of classes named "someclass.h" do indeed follow good C++ OOP practices.

However, if one includes more than one "independent.cpp" into a build, it is likely to run into name conflicts. The actual name conflicts could be two "static" variables with the same name ("var1") across two such source files (*), or could be linking errors.

(*) Unless they are made extern. Remember these lines are being included into a single cpp file.

So, one could deduce that in an actual build, only one such "independent.cpp" file could ever be linked per executable produced in the build. If there are multiple files like this, only one of these could be linked at a time.

(Details.)

Suppose there were two files, "IndependentOne.cpp" and "IndependentTwo.cpp". Note that these file extensions wouldn't matter, if they were being included verbatim into another cpp file.

Suppose each "IndependentOne.cpp" and "IndependentTwo.cpp" contains a definition for "var1":

```<code>// IndependentOne.cpp
#include "someClassOne.h"
static someClassOne var1;

// IndependentTwo.cpp
#include "someClassTwo.h"
static someClassTwo var1;

// SomeMainFile.cpp
#include "IndependentOne.cpp"
#include "IndependentTwo.cpp"  // ---- compiler error here
int main(int argc, char** argv)
{ ... }
</code>```

Then var1 is multiple-defined. To resolve it, one has to manually copy-and-paste the two files together, into "IndependentOneAndTwo.cpp", and rename the static variables.

When is it appropriate?

Whenever you need to "call a C++ function from the OS command line",

You want one executable file per C++ function called

No data passed between calls; or the data is always passed via the file system

What the heck is this philosophy?

It sounds like Unix-ish - Do one thing and do it well; chain your programs with pipes

It would have been more believable, if it was not betrayed by the hard-coded filename "file.txt"

If it is not meant to be for real use (hard-coded filenames, etc) then what is it used for?

Throwaway "command line wrappers" for C++ functions.

It allows you to call exactly one C++ function;

It reads from and writes to exactly one file or directory, whose path is hard-coded.

What are some alternative designs?

If your goal is throwaway command-line wrapper, this is fine.

As long as these files are excluded from the production build.

If your goal is production use command-line application,

Implement or use a decent command-line parsing utility, or integrate a small scripting engine with your C++ classes which removes the "call once and exit" limitation.

If your goal is software testing (white-box / unit-testing),

Use a unit testing framework.

Title: Only functions without a class in cpp file! good design or not?

Body:
When I was going through the project on which I am working, I came across a cpp file, which has only functions and static variables.I was wondering why they have not put everything into a class! Whenever the inside functions have to be called, the cpp file is included.

Is this a good design? what are the pros and cons of these type of design?

for ex.

```<code>//independent.cpp
#include "someclass.h"
static int var1;
static someclass object("hello");
static bool var2;

void foo(const char* dir, const char* filename){
...
}

somefile.cpp
#include "independent.cpp"
class sample{
public:
  void caller(){
  foo("c:\", "file.txt");
  }
}
</code>```

Body:
My guess is that it is used to make a bunch of "single purpose executables".

(Disclaimer: my C++ knowledge is not as good as the other answerers - my answer is just a guess.)

Observe that

This approach allows multiple reusable classes, "someclass.h", etc, to be included. So, one could deduce that the family of classes named "someclass.h" do indeed follow good C++ OOP practices.

However, if one includes more than one "independent.cpp" into a build, it is likely to run into name conflicts. The actual name conflicts could be two "static" variables with the same name ("var1") across two such source files (*), or could be linking errors.

(*) Unless they are made extern. Remember these lines are being included into a single cpp file.

So, one could deduce that in an actual build, only one such "independent.cpp" file could ever be linked per executable produced in the build. If there are multiple files like this, only one of these could be linked at a time.

(Details.)

Suppose there were two files, "IndependentOne.cpp" and "IndependentTwo.cpp". Note that these file extensions wouldn't matter, if they were being included verbatim into another cpp file.

Suppose each "IndependentOne.cpp" and "IndependentTwo.cpp" contains a definition for "var1":

// IndependentOne.cpp
#include "someClassOne.h"
static someClassOne var1;

// IndependentTwo.cpp
#include "someClassTwo.h"
static someClassTwo var1;

// SomeMainFile.cpp
#include "IndependentOne.cpp"
#include "IndependentTwo.cpp"  // ---- compiler error here
int main(int argc, char** argv)
{ ... }

Then var1 is multiple-defined. To resolve it, one has to manually copy-and-paste the two files together, into "IndependentOneAndTwo.cpp", and rename the static variables.

When is it appropriate?

Whenever you need to "call a C++ function from the OS command line",

You want one executable file per C++ function called

No data passed between calls; or the data is always passed via the file system

What the heck is this philosophy?

It sounds like Unix-ish - Do one thing and do it well; chain your programs with pipes

It would have been more believable, if it was not betrayed by the hard-coded filename "file.txt"

If it is not meant to be for real use (hard-coded filenames, etc) then what is it used for?

Throwaway "command line wrappers" for C++ functions.

It allows you to call exactly one C++ function;

It reads from and writes to exactly one file or directory, whose path is hard-coded.

What are some alternative designs?

If your goal is throwaway command-line wrapper, this is fine.

As long as these files are excluded from the production build.

If your goal is production use command-line application,

Implement or use a decent command-line parsing utility, or integrate a small scripting engine with your C++ classes which removes the "call once and exit" limitation.

If your goal is software testing (white-box / unit-testing),

Use a unit testing framework.


问:
Guessing a phone number's country code
This is the problem I'm working with: given a phone number from anywhere in the world and some location information (state, province, possibly country name if I'm lucky, etc.), return the ISO country code for that number.

For the purposes of this question, I will not focus on the location information, as that provides an alternative solution to determining the country code which doesn't even need to use the phone number anymore (though, it would be useful for validation purposes)

When I first started working on the problem, I was hoping there was a deterministic way to figure this out because there was some sort of international standard out there. It became immediately apparent that one does not exist for phone numbers. There are standards within countries, between countries (NANP for example), but no unified international standard.

Playing around with libphonenumbers for a few days, it seems to be able to provide accurate validation of a phone number if I'm given a country code (eg: CA for Canada, GB for United Kingdom, etc).

The library provides two methods: isPossibleNumber, and isValidNumberForRegion. This is the code I'm using

```<code>boolean isValid;
PhoneNumber number;
PhoneNumberUtil util = PhoneNumberUtil.getInstance();

String numStr = "(123) 456-7890";
for (String r : util.getSupportedRegions())
{
    try {
        // check if it's a possible number
        isValid = util.isPossibleNumber(numStr, r);
        if (isValid)
        {
            number = util.parse(numStr, r);

            // check if it's a valid number for the given region
            isValid = util.isValidNumberForRegion(number, r);
            if (isValid)
                System.out.println(r + ": " + number.getCountryCode() + ", " + number.getNationalNumber());
        }
    } catch (NumberParseException e)
    {
        e.printStackTrace();
    }
}
</code>```

So for example, if I took an arbitrary phone number like +44 20 7930 4832 and ran it through the method, I would get the following output

```<code>GB: 44, 2079304832
</code>```

Now, that's assuming I'm given the dialing code (sometimes it's there). If I weren't given the dialing code, I might just get something like 20 7930 4832, and the results are not as pretty

```<code>DE: 49, 2079304832
US: 1, 2079304832
GB: 44, 2079304832
FI: 358, 2079304832
AX: 358, 2079304832
RS: 381, 2079304832
CN: 86, 2079304832
NZ: 64, 2079304832
IN: 91, 2079304832
IR: 98, 2079304832
JP: 81, 2079304832
</code>```

Given a phone number, I can run it through all of the different rules for every country and filter the list down from 244 to around 20 or less if I'm lucky, but I'm not sure if there's anything else I could do to try and guess the country.

答:
Telephone switches can figure this out, so there must be some method to the madness.  And, in fact, there is:

Country codes are arranged in a tree, where you start at the root and descend into a subtree depending on the value of each digit.  When you've reached a leaf node, you're at something that could be a country code.  Any digits beyond those you've used to find a leaf node in a tree are would would have to be decoded according to the local numbering plan.

For example, the +1 country code is easy:  it covers the North American Numbering Plan.  Any number beginning with +1 will fall into that plan; there are no other countries within it with numbers like +12 or +123.  If you want to know whether a +1 number is the U.S. or Canada, you'd have to look up the next three digits (the area code) in a table that will tell you that information.  (Russia, Kazakhstan and a few other territories are the same way on the Russian numbering plan, which occupies the entire +7 branch.)

The +2 branch has ten sub-branches.  All of +20 is Egypt, +27 is South Africa and +28 is unassigned.  As above, no countries other than Egypt have a country code that starts with +20.  The remaining seven prefixes are divided ten ways each.  +21 is subdivided ten ways into +210 through +219 and covers countries like South Sudan, Morocco and Algeria.  +22 is divided into +220 through +229 for The Gambia, Senegal, Mauritania, etc.

The tree you need for this can be easily generated from a list of the country codes and their countries.

Title: Guessing a phone number's country code


问:
How important is XML for a developer?
Is it must that every developer should know XML? How important is XML for a developer? Any suggestion...</p>

答: It is helpful to at least know what it is and the basics of XPath. But these days JSON has taken over the data transfer format of choice for most web developers.</p>

ContentLicense: CC BY-SA 2.5

Title: How important is XML for a developer?


问:
Why is Java not 'pure' OOP?
Java is designed in a very OO approach, and somewhat even 'forces' programmers to program within the OO paradigm (which can be considered good or bad, a matter of opinion).

However while almost everything in Java is a class or an object, primitive data types (int, double, etc) are not.

While I see no advantages to this, there are disadvantages. For example, when a method wants to take in as a parameter 'any value', it usually declares the parameter of type Object, the supertype of all classes in Java. However if the programmer wants to input an int to the method - a perfectly valid value - he/she has to 'box' the value in an instance of the Integer class, created specifically for these kinds of needs (as far as I understand).

My question is: why aren't primitives in Java classes, like everything else?

答:
Quoting an answer of mine in another question.

In some cases language designers make compromises for usability's sake.

Numbers are used too often. Having to instantiate them all the time would make the language too verbose.

There a few other examples of special exceptions made for the sake of usability:

Objects of type String can be instantiated without new, event when String is not a primitive:

```<code>String s = "Hello";
</code>```

String being a non-primitive, should be instanciated like this:

```<code>String s = new String("Hello");          // this also works
</code>```

But the compiler allows for the shorter, less OO option, because String is by far the most widely used class in the API.

Also arrays can be initialized in a non-OO way:

```<code>int i[] = {1,2,3};
</code>```

Weird enough, an object is either an instance of a class or an array. Meaning arrays are a completely separate type of class.

Arrays have a lenght public field which is not a constant. Also there's no documentation on the class arrays are an instance of. ( not to confuse with Arrays class or java.reflect.Array ).

```<code>int a = myArray.length;    // not length()
</code>```

Title: Why is Java not 'pure' OOP?

Body:
Quoting an answer of mine in another question.

In some cases language designers make compromises for usability's sake.

Numbers are used too often. Having to instantiate them all the time would make the language too verbose.

There a few other examples of special exceptions made for the sake of usability:

Objects of type String can be instantiated without new, event when String is not a primitive:

String s = "Hello";

String being a non-primitive, should be instanciated like this:

String s = new String("Hello");          // this also works

But the compiler allows for the shorter, less OO option, because String is by far the most widely used class in the API.

Also arrays can be initialized in a non-OO way:

int i[] = {1,2,3};

Weird enough, an object is either an instance of a class or an array. Meaning arrays are a completely separate type of class.

Arrays have a lenght public field which is not a constant. Also there's no documentation on the class arrays are an instance of. ( not to confuse with Arrays class or java.reflect.Array ).

int a = myArray.length;    // not length()


答:
One core principle of OOP is that values (not just variables) have types, which is a requirement for dynamic dispatch. Each object is tagged with a type. This tag is usually a pointer to a structure representing a class. In Java, objects have further overhead to facilitate synchronization, but lets be aware that each object has to at least carry a pointer (4 or 8 bytes) around together with the actual data. This alone doubles or quadruples the size of a primitive like int! Having primitives that aren't real objects is therefore very desirable from a performance standpoint.

Having primitives is not a problem – C# is very similar in that respect, except that real autoboxing makes explicit companion classes like Integer unnecessary.

In Java there is also some connection between primitives and generics. Due to Java's history, generics have been implemented using type erasure: at runtime, there is no difference between a List<Foo> and a List<Integer>, as the generic types are only checked during compilation. In reality, such generic collections just contain Objects. Generics can also be implemented efficiently using specialization (which is how templates in C++ work). As we can now figure out whether we have a List<Foo> or List<int>, we can use compact storage for primitive types (or in principle other sealed/final classes). Java can't do that, so we need full blown objects when storing primitives in collections – here, an Integer wrapper.

Such issues with generics were not on the horizon when Java was first released. Gradually, more and more autoboxing behaviour has been added to make this divide less visible.

Title: Why is Java not 'pure' OOP?

Body:
Java is designed in a very OO approach, and somewhat even 'forces' programmers to program within the OO paradigm (which can be considered good or bad, a matter of opinion).

However while almost everything in Java is a class or an object, primitive data types (int, double, etc) are not.

While I see no advantages to this, there are disadvantages. For example, when a method wants to take in as a parameter 'any value', it usually declares the parameter of type Object, the supertype of all classes in Java. However if the programmer wants to input an int to the method - a perfectly valid value - he/she has to 'box' the value in an instance of the Integer class, created specifically for these kinds of needs (as far as I understand).

My question is: why aren't primitives in Java classes, like everything else?


答:
I think the only reason is that it is complicated for the compiler writer.

I mean, you could have a system where every primitive type was used in the language as if it were any object with all the "elegance" and convenience that entails. So a call to string s = i.ToString(); would become a call to the equivalent static function string s = ToString(i); as a simplistic example.

However, you'd have to tell which types were primitive and which were not; you'd also have to ban inheriting from these (or you could get in all kinds of a mess); and even then some people would create their own pseudo-primitive types and expect them to perform with the speed of primitives.

But I think some aspects of objects would prove to be too difficult to implement in such a fashion for primitives - garbage collection requires all objects be created on the heap and referenced and the interfaces that are expected by method calls wouldn't necessarily work if there wasn't a real interface to call through (ie each object needs a vtable which our primitives-as-objects wouldn't have)

So boxing is a workaround that was added. I think the C++ way is better - no boxing required there and you can mix primitives and objects easily. Java went for a higher level abstraction and this way of having to work with primitives differently is just another example of real world impacting on our desire for perfection.

Title: Why is Java not 'pure' OOP?


答:
There are trade offs to be had in every design choice.

When you have a "pure" OO language (see if you can get anyone to agree on what that is), when you do addition, rather than having the system get two numbers and add them, you are instead first invoking the add method on the object and getting back a new one (making mutable Number Objects can make for difficult times).

An example of this would be the BigInteger class.  Instead of int fourtyTwo = 6 * 7; you've got BigInteger fourtyTwo = new BigInteger(6).multiply(new BigInteger(7));  You've created a total of three objects and done some math in the background.  This is also a little bit of a mess, but thats just the semantics - you can hide that with operators, but its still doing all that work behind it.

From C2 Is Java Object Oriented the reason becomes clear:

Lastly, it is a hybrid to provide performance gains. Even though Smalltalk has an advanced virtual machine, its inability (when I was using it) to provide a machine-correlated bytecode for integer math placed a significant performance impact on its entire environment. Being a hybrid, Java cannot be called a true Object-Oriented language. But then, why does it matter? ;-) Use the right tool for the job and life will be happy!

You can see what is being mentioned there in some docs for SmallTalk:

Thus, math is not a special case in Smalltalk; it is done, exactly like everything else, by creating objects, and sending them messages. This may seem odd to the Smalltalk novice, but this regularity turns out to be quite a boon: once you've mastered just a few paradigms, all of the language “falls into place”. Before you go on to the next chapter, make sure you try math involving * (multiplication), - (subtraction), and / (division) also. These examples should get you started:

While yes, it does men that some things can be more elegant in the language design it also means that its going to be slower.  From a talk on SmallTalk and Objective C:

What makes things slow?

Small integer arithmetic

Boxing

Dynamic message lookup

Memory management operations

Another example of this performance can be seen at the Language Benchmarks Game for Ruby vs Java - where Ruby implements the "pure" OO style math - messages are sent to the object to add rather than working with primitives.  Note that in many cases Ruby is one or two orders of magnitude slower than Java.  These benchmarks are all math heavy, and when looking at the Java code, they're all using primitives.

There are things you can do to speed that up, but its still less than optimal.  Early Java was plagued by performance concerns.  Making math that much slower would have been awful.

Lets look at a high performance Java architecture: LMAX.  Every iota of performance was pulled out of this, in some cases rewriting some rather basic things.

It took a bit more cleverness to go up another order of magnitude. There are several things that the LMAX team found helpful to get there. One was to write custom implementations of the java collections that were designed to be cache-friendly and careful with garbage. An example of this is using primitive java longs as hashmap keys with a specially written array backed Map implementation (LongToObjectHashMap). In general they've found that choice of data structures often makes a big difference, Most programmers just grab whatever List they used last time rather than thinking which implementation is the right one for this context.

Writing a HashMap that could work on <long, Object> rather than <Long, Object> allowed for some significant performance gains by not having to do object based equality for two objects (could just use ==) and avoiding a number of issues with garbage collection (look at your heap some time and count how many Long objects are sitting around when you're heavily using HashMaps).

Lastly consider that Java's hotspot optimizer will compile code to native when it needs to.  The code produce by int fourtyTwo = 6 * 7 is much simpler and faster than the corresponding BigInteger fourtyTwo = new BigInteger(6).multiply(new BigInteger(7));

Its all about trade offs, and this was one where performance won out over "pure" elegance.

Title: Why is Java not 'pure' OOP?

ContentLicense: CC BY-SA 4.0


答: It is always good to know the different data formats like XMl, RRDBMS, CSV etc. Also it will be helpful to know basics of how it works, advantages and limitations of each. This will certainly help taking some important decisions at the design stage. In light of this I will say it is important for developers to know basics of the XML, XPATH, validations, dtd, xsl. But it will not be mandatory to know the low level implementation details. </p>

Title: How important is XML for a developer?

Body: Is it must that every developer should know XML? How important is XML for a developer? Any suggestion...</p>


问:
Single Page Web Application Web Service Scalability
I am trying to build a single page web application that will call multiple web services (both SOAP and RESTful) and aggregate the data in the UI.

Initially I though I could do it all client-side, with ajax requests, but I realize that

If there are many requests, and they are fired per user, the data can take a long time to load.

If there are a lot of users, then I can easily reach my limit of API calls.

So now I'm thinking that I will have to have some kind of server-side process that runs every hour (or whatever), retrieves the items, and inserts/updates them in a database.  Is this the right approach?  Are there any other pitfalls I need to avoid?

答:
Whether your web app is a single page design or a more traditional multi-page design your concern about API call limits applies equally.

If you haven't already become friends with memcache (or similar service on your platform).

You don't necessarily have to setup a cron to run once an hour.

Whenever a user requests information that requires a third-party service call:

For first time calls, make API call to third party service

After getting a successful response back from API call, cache the result

Set cache expiration time to a value that makes sense for that type of data (some data can be cached for a week, while other data should only be cached for a few minutes)

Every subsequent request for data, check if the cache exists and has not expired for that piece of data, if so return it, otherwise, go to step #1

A bonus of using a caching system similar to memcache is speed, since the data sits in memory it is orders of magnitude faster than a database query or making a third-party API call.


答:
it's only important to know it when you need it

and when you need it, you can learn it in an hour. or less

Title: How important is XML for a developer?


问:
Using a Simple/Static Factory vs. instantiating directly: new Thing() vs. factory.createThing() - what's the benefit?
Here are two ways to instantiate an object:

Option 1:

```<code>Thing thing = new Thing();
</code>```

Option 2: (the factory is a Static Factory, but it could also be a Simple Factory).

```<code>Thing thing = ThingFactory.createThing();
</code>```

Where:

```<code>class ThingFactory(){
    public static Thing createThing(){
        return new Thing();
    }
}
</code>```

Option 2 is said to be better, because using a factory decouples the client code from the concrete implementation of the class it's instantiating.

However what difference does it actually make if I use new Thing() or factory.createThing()? The only difference between the two options is that the instantiation code is moved to a different place.

As I explained above I know the 'academic' explanation to why using a factory is 'better', but I don't actually see the practical benefit. In both cases, the client knows exactly what it wants: a Thing. The only difference is the exact line of code: new Thing() or factory.createThing().

More sophisticated factories, I can see their benefit. For example using the Abstract Factory pattern, I could create different Factory subclasses that instantiate different concrete implementations of Thing, and inject the suitable Factory to the client at runtime, without the client worrying about the concrete implementation it receives. BlueThingFactory instantiates BlueThing, RedThingFactory instantiates RedThing, but the client only cares that it receives a Thing.

This is with more sophisticated factories.

But I'm unable to see the benefit of using a simple factory as in the example I described. All it does is move new Thing() to a different place. I don't understand the benefit of this.

Please explain to me the actual benefits of using a simple factory.

答:
There is none. Actually, using factory in this simple case might be counterproductive, because you are adding new class for zero benefit. And any kind of argument that says there is a benefit shifts from this simple method call to more sophisticated factory. Which as you said, do have benefits.

So according to YAGNI, if you don't expect the class of instance to be supplied from the outside or require some kind of special creation logic, there is absolutely no need to create a specific factory class. Actually, constructors are meant to be such simple factories.

I believe massive use of factories and design patterns like this is great example of cargo-cult programming. Where people use patterns haphazardly without actually knowing what kind of problems the patterns are meant to solve. And it is one of the reasons why Java is considered bloated.


答:
It's "better", because you get fewer dependencies.

One of the worst things in software development is dependencies. Dependencies makes it very difficult to modify the software later on. Circular dependencies are even worse.

When you say new Thing() your client code now relies on the concrete class of thing. You have created a hard dependency from your client code to a very specific class, Thing.

When you say factory.CreateThing() any class that supplies the required interface can be used, and you client code no longer has a dependency to a concrete class.

But choosing which is "better" is a balance of many factors, and introducing factories for all your domain concepts will add other complexities to the code, and take time more to write. So it may be better from an architectural point of view, but not necessarily better from a practical point of view, if the complexity of the application does not benefit significantly from this abstraction.

Title: Using a Simple/Static Factory vs. instantiating directly: new Thing() vs. factory.createThing() - what's the benefit?

Body:
Here are two ways to instantiate an object:

Option 1:

```<code>Thing thing = new Thing();
</code>```

Option 2: (the factory is a Static Factory, but it could also be a Simple Factory).

```<code>Thing thing = ThingFactory.createThing();
</code>```

Where:

```<code>class ThingFactory(){
    public static Thing createThing(){
        return new Thing();
    }
}
</code>```

Option 2 is said to be better, because using a factory decouples the client code from the concrete implementation of the class it's instantiating.

However what difference does it actually make if I use new Thing() or factory.createThing()? The only difference between the two options is that the instantiation code is moved to a different place.

As I explained above I know the 'academic' explanation to why using a factory is 'better', but I don't actually see the practical benefit. In both cases, the client knows exactly what it wants: a Thing. The only difference is the exact line of code: new Thing() or factory.createThing().

More sophisticated factories, I can see their benefit. For example using the Abstract Factory pattern, I could create different Factory subclasses that instantiate different concrete implementations of Thing, and inject the suitable Factory to the client at runtime, without the client worrying about the concrete implementation it receives. BlueThingFactory instantiates BlueThing, RedThingFactory instantiates RedThing, but the client only cares that it receives a Thing.

This is with more sophisticated factories.

But I'm unable to see the benefit of using a simple factory as in the example I described. All it does is move new Thing() to a different place. I don't understand the benefit of this.

Please explain to me the actual benefits of using a simple factory.


问:
Terms in conditions in installer or is on website ok
I am currently in the process of packing my first c# wpf app.

The app will be paid so it requires the user to agree to some terms and conditions.

Is it best to have these built into the installer? Or can I get away with having the user accept them on the website they buy them from during the purchase and before download the app?

答:
The app will be paid so it requires the user to agree to some terms and conditions.

Really? In my country, courts have ruled that nobody actually reads all the legalese and nobody in their right mind can really expect people to read this, so it's not a binding contract anyway.

If anyone had to read and understand and agree to Apples ToS, they would not have sold a single iProduct. Companies' business model includes customers clicking through all the "terms and conditions".

If you want people to read anything you write, put it where they will read it. Put in in simple sentences next to their credit card number when they pay. Simple sentences means one, maybe two paragraphs and no legalese. This is how you get information across.

If you need 9 pages of legalese to make your application look "commercial", feel free to put it whereever you want.

If you need a binding contract, consult a lawyer, this probably won't work without actual paperwork between you and your customer.


问:
Japanese Multiplication simulation - is a program actually capable of improving calculation speed?
I'd like to write a simulation of Japanese Multiplication to get benchmarks on large calculations utilizing the shortcut vs traditional CPU multiplication. I'm curious as to whether it makes sense to try this.

My Question: I'd like to know whether or not a software math shortcut, as described above is actually a shortcut at all.

This is a question of programming concept. By utilizing the simulation of Japanese Multiplication, is a program actually capable of improving calculation speed? Or am I doomed from the start?

The answer to this question isn't required to determine whether or not the experiment will succeed, but rather whether or not it's logically possible for such a thing to occur in any program, using this concept as an example.

My theory is that since addition is computed faster than multiplication, a simulation of Japanese multiplication may actually allow a program to multiply (large) numbers faster than the CPU arithmetic unit can. I think this would be a very interesting finding, if it proves to be true.

If, in the multiplication of numbers of any immense size, the shortcut were to calculate the result via less instructions (or faster) than traditional ALU multiplication, I would consider the experiment a success.

答:
This multiplication algorithm does not replace multiplication with addition. Instead, it splits the multiplication into a number of smaller multiplications that are easier for humans to understand. Humans (unlike computers) deal well with patterns and symbols, less so with large numbers (where “large“ means “multiple digits”).

```<code>321 × 254

  × |  2E2 +  5E1 +  4E0
----|-------------------
3E2 |  6E4 + 15E3 + 12E2
 +  |   +      +      +
2E1 |  3E3 + 10E2 +  8E1
 +  |   +      +      +
1E0 |  2E2 +  5E1 +  4E0

SUM = 81534
</code>```

Those weird diagonals in your picture just group the small multiples with the same exponent together, which makes adding easier.

This algorithm can immediately be generalized to the multiplication of big integers, by dividing the input numbers into pieces half the size of native integers. The lower half of an integer is then the “first digit”, the upper half is the carry digit. Remember that a multiplication of two n-bit integers results in a 2n-bit integer, which is why we need that extra space. During addition, possible overflows have to be handled manually (which makes this algorithm inefficient).

So we could apply this algorithm to base 216 or base 232.
It is not appropriate to apply this algorithm to base 2: here builtin multiplication will very likely be faster than anything else.

Your “Japanese Multiplication” is just a visual interpretation of lattice multiplication. It suffers from having O(n²) complexity, and faster algorithms exist.

Body:
This multiplication algorithm does not replace multiplication with addition. Instead, it splits the multiplication into a number of smaller multiplications that are easier for humans to understand. Humans (unlike computers) deal well with patterns and symbols, less so with large numbers (where “large“ means “multiple digits”).

321 × 254

  × |  2E2 +  5E1 +  4E0
----|-------------------
3E2 |  6E4 + 15E3 + 12E2
 +  |   +      +      +
2E1 |  3E3 + 10E2 +  8E1
 +  |   +      +      +
1E0 |  2E2 +  5E1 +  4E0

SUM = 81534

Those weird diagonals in your picture just group the small multiples with the same exponent together, which makes adding easier.

This algorithm can immediately be generalized to the multiplication of big integers, by dividing the input numbers into pieces half the size of native integers. The lower half of an integer is then the “first digit”, the upper half is the carry digit. Remember that a multiplication of two n-bit integers results in a 2n-bit integer, which is why we need that extra space. During addition, possible overflows have to be handled manually (which makes this algorithm inefficient).

So we could apply this algorithm to base 216 or base 232.
It is not appropriate to apply this algorithm to base 2: here builtin multiplication will very likely be faster than anything else.

Your “Japanese Multiplication” is just a visual interpretation of lattice multiplication. It suffers from having O(n²) complexity, and faster algorithms exist.


答:
Unsurprisingly, you are indeed "doomed from the start".

This "Japanese Multiplication" (which is a visual form of the grid method tought in UK primary schools since the 1990s) has a time complexity of at least O(n^2) where n is the number of digits in the numbers you are multiplying. This is because the number of intersections will be n*n, and you have to deal with each of them.

This is the same as traditional long multiplication.

Toom-Cook-multiplication is about O(n^1.465), and there are better ones by now (their complexity isn't a straight exponential though).

Title: Japanese Multiplication simulation - is a program actually capable of improving calculation speed?

Body:
I'd like to write a simulation of Japanese Multiplication to get benchmarks on large calculations utilizing the shortcut vs traditional CPU multiplication. I'm curious as to whether it makes sense to try this.

My Question: I'd like to know whether or not a software math shortcut, as described above is actually a shortcut at all.

This is a question of programming concept. By utilizing the simulation of Japanese Multiplication, is a program actually capable of improving calculation speed? Or am I doomed from the start?

The answer to this question isn't required to determine whether or not the experiment will succeed, but rather whether or not it's logically possible for such a thing to occur in any program, using this concept as an example.

My theory is that since addition is computed faster than multiplication, a simulation of Japanese multiplication may actually allow a program to multiply (large) numbers faster than the CPU arithmetic unit can. I think this would be a very interesting finding, if it proves to be true.

If, in the multiplication of numbers of any immense size, the shortcut were to calculate the result via less instructions (or faster) than traditional ALU multiplication, I would consider the experiment a success.


问:
tracking time for personal projects
Does everyone track time spent on personal projects? I feel that it is valuable to know how much time (and potential money) has been put into a hobby.

I am currently using harvest to track time.

答:
I am not used to track my time for my personal projects. But I do track time for my freelance projects.

My personal projects are more of experimental things. So, I don't really feel the need to track that time. But, once the personal projects starts making money, I guess it's a good idea to track the amount of time spent.

Title: tracking time for personal projects


答:
If it's a simple object with a simple factory (like your example) then there is no advantage.  I would be very leery of putting it in a factory (just in case vs YAGNI).

Things get interesting as the system changes and that simple object starts gathering behavior.

Adding an argument

When I add an argument to the constructor, I'm faced with a decision.  Overload the constructor or change all the client code to use this new argument.

If it's optional, then overloading the constructor feels natural.

But what if this is now a required field?

If the object in question is a value object, then I've likely created dozens of them in my tests.  At this point I almost always create a test-only factory for that value object so I can keep adding default test data without modifying lots of tests.  This can be applied in the general case, but it's also a smell if you need a factory for every kind of test, what are you really testing?

If it's not a value object then I'm likely to add the argument everywhere, hopefully I haven't made too many of these.

Adding a second/third argument

At this point I should have a good idea of what this object is.

If it's a value object, then I just roll with the previous strategy.  I wouldn't necessarily create a "factory" but it seems like I need some centralized place to create these values.  This is often the case when translating data from one format to what my system needs.

If it is something else, how many places do I instantiate this code?  If just one place, just add the argument in place.  That's natural, it's where you discovered you needed this one more thing.

If it's in lots of places, does it make sense to use this object in all those places?  If it's something like a logger, then yes it does.  Time to build a factory.

If it's something domain-specific without cross-cutting-concerns then I need to take a hard look.  Why is this thing useful in so many places?  Is it doing too much?  Split it into the concerns that each dependency is needed for.

If it's tightly focused but needs a lot of things to do it's job then a factory seems appropriate.  Sometimes it's a thing like validation rules.  You can work towards centralizing that, but a layered defense often makes sense.  One other angle you can look at is if all the arguments being passed in perhaps belong together, like in a ParameterObject or something more appropriate.

Mixing in some behavior at construction time

Need object pooling?  Sharing a connection? Need a singleton?  Need to add debugging/logging?  This is the natural fit for factories.

Creating specialized objects with arguments supplied

My personal preference for factories is to create expressive names.  This is especially useful when following a dependency injection type style.

```<code>StormMaker.createThunderStorm()  // new Storm(80, 20, 360000, Thunder, Lightning)
StormMaker.createTornado()       // new Storm(70, 100, 60000, Lightning)
StormMaker.createBlizzard()      // new Storm(30, 30, 43200000)
</code>```

Body:
If it's a simple object with a simple factory (like your example) then there is no advantage.  I would be very leery of putting it in a factory (just in case vs YAGNI).

Things get interesting as the system changes and that simple object starts gathering behavior.

Adding an argument

When I add an argument to the constructor, I'm faced with a decision.  Overload the constructor or change all the client code to use this new argument.

If it's optional, then overloading the constructor feels natural.

But what if this is now a required field?

If the object in question is a value object, then I've likely created dozens of them in my tests.  At this point I almost always create a test-only factory for that value object so I can keep adding default test data without modifying lots of tests.  This can be applied in the general case, but it's also a smell if you need a factory for every kind of test, what are you really testing?

If it's not a value object then I'm likely to add the argument everywhere, hopefully I haven't made too many of these.

Adding a second/third argument

At this point I should have a good idea of what this object is.

If it's a value object, then I just roll with the previous strategy.  I wouldn't necessarily create a "factory" but it seems like I need some centralized place to create these values.  This is often the case when translating data from one format to what my system needs.

If it is something else, how many places do I instantiate this code?  If just one place, just add the argument in place.  That's natural, it's where you discovered you needed this one more thing.

If it's in lots of places, does it make sense to use this object in all those places?  If it's something like a logger, then yes it does.  Time to build a factory.

If it's something domain-specific without cross-cutting-concerns then I need to take a hard look.  Why is this thing useful in so many places?  Is it doing too much?  Split it into the concerns that each dependency is needed for.

If it's tightly focused but needs a lot of things to do it's job then a factory seems appropriate.  Sometimes it's a thing like validation rules.  You can work towards centralizing that, but a layered defense often makes sense.  One other angle you can look at is if all the arguments being passed in perhaps belong together, like in a ParameterObject or something more appropriate.

Mixing in some behavior at construction time

Need object pooling?  Sharing a connection? Need a singleton?  Need to add debugging/logging?  This is the natural fit for factories.

Creating specialized objects with arguments supplied

My personal preference for factories is to create expressive names.  This is especially useful when following a dependency injection type style.

StormMaker.createThunderStorm()  // new Storm(80, 20, 360000, Thunder, Lightning)
StormMaker.createTornado()       // new Storm(70, 100, 60000, Lightning)
StormMaker.createBlizzard()      // new Storm(30, 30, 43200000)


答:
...is a program actually capable of improving calculation speed? Or am I doomed from the start?

In pathological cases that are no longer relevant because the environments in which they occurred have fallen into disuse, probably.  In practical situations where you're making apples-to-apples comparisons, not on your life.

Look at speed in terms of instruction cycle budget.  On Intel CPUs, an integer multiply has a latency of three cycles.  That's your budget.  Anything you do has to beat that number to be considered an improvement.  Three cycles isn't much.

Let's be very generous and go on the assumption that the numbers you're handed are in binary-coded decimal (e.g., the decimal number 1234 is represented as 0x1234).  This means that there's no multiplication involved, just logical shifts and AND operations to mask off the digit we want.  Those consume one cycle each (less depending on the state of the pipeline, but let's not complicate it).  Isolating a digit therefore takes two cycles, storing it someplace to be dealt with later is a third and incrementing the counter for where it's stored is a fourth.  The three-cycle budget has been exceeded by 33% just doing the first digits' worth of prep for your shortcut.

Like early CPUs, humans don't have a built-in multiplication instruction, so it has to be done the hard way.  If you get good enough with the shortcut, odds are good you'll be able to do large multiplications in fewer mental cycles than doing it the long way.  But, as Michael Borgwardt's answer points out, this is still long multiplication that's been optimized to run faster in wetware.  CPUs do it in ways that have been optimized to run faster in electrical circuits.  Multiplication is a new enough concept that another hundred million years may pass before we evolve groups of neurons that can do it instantly.  We probably won't, because we've figured out how to get our machines to do it on our behalf.


问:
Should I implement a function or a method?
Once in a while I encounter a C function in my colleagues' code.
Mostly it is in some helpful objective categories,  and those functions are mostly an internal calculation of something or a comparison of values.

Since those guys are not part of the company anymore, I can't ask them why they decided to go with a C function instead of a proper objective C method.

So the question is:

Why implement certain algorithms as a C function instead of objective C method?
What are the considerations?

答:
Most of the time you'll want methods. But remember that methods imply all kinds of overhead. So, if you don't have to use methods, using C functions can be a clever choice.

You should choose methods if:

other code is going to directly access that functionality. Methods are a convenient way of namespacing functions; the C way of adding cryptic prefixes does not scale.

your architecture requires dynamic dispatch. The Visitor Pattern is a very good example of this.

your functionality is semantically behaviour of an object. Getters/setters are an example of such functionality.

You should choose C functions if:

performance is critical. Calling a C function tends to be cheaper than invoking a method. Mathematical helper functions could be an example.

no other code will use that functionality – it's an internal helper.

the functionality does not require OOP features like dynamic dispatch to be called. It may still call methods on objects internally. That is, you are writing a procedure or subroutine, not a method.

your functionality is semantically some operation that only incidentally happens to have objects as arguments. I.e. the subject of interest is the action, not the object.

If you'd have a private static “method” for that functionality in Java, it's extremely likely that this should be a C function in Objective-C.


问:
Maintaining referential integrity between a mobile client and a server
So I have a relatively simple system. A mobile client creates records in a sqlite database that I would like to have synced to a remote SQL server (that is shared with other mobile clients). So when I create a new record in the phone's sqlite table, I then push that change to my remote service through a RESTful API. The problem I'm having, is how do I order the primary keys so that there isn't collisions in the data (i.e. a record in the phone has the same primary key as a completely different record on the server). What is the usual "best practice for referencing the record on the client, and for referencing the same record on the server?

答:
I have the same issue with a project i am working on, the solution in my case was to create an extra nullable field in the local tables named remote_id. When synchronizing records from local to remote database if remote_id is null, it means that this row has never been synchronized and needs to return a unique id matching the remote row id.

```<code>Local Table            Remote Table

_id (used locally)
remote_id ------------- id
name      ------------- name
</code>```

In the client application i link tables by the _id field, remotely i use the remote id field to fetch data, do joins, etc..

example locally:

```<code>Local Client Table       Local ClientType Table      Local ClientType
                         _id
                         remote_id
_id -------------------- client_id
remote_id                client_type_id -------------- _id
                                                      remote_id
name                    name                          name
</code>```

example remotely:

```<code>Remote Client Table      Remote ClientType Table      Remote ClientType
id -------------------- client_id
                        client_type_id -------------- id
name                    name                          name
</code>```

This scenario, and without any logical in the code, would cause data integrity failures, as the client_type table may not match the real id either in the local or remote tables, therefor whenever a remote_id is generated, it returns a signal to the client application asking to update the local _id field, this fires a previously created trigger in sqlite updating the affected tables.
http://www.sqlite.org/lang_createtrigger.html

1- remote_id is generated in the server

2- returns a signal to client

3- client updates its _id field and fires a trigger that updates local tables that join local _id

Of course i use also a last_updated field to help synchronizations and to avoid duplicated syncs.

Body:
I have the same issue with a project i am working on, the solution in my case was to create an extra nullable field in the local tables named remote_id. When synchronizing records from local to remote database if remote_id is null, it means that this row has never been synchronized and needs to return a unique id matching the remote row id.

Local Table            Remote Table

_id (used locally)
remote_id ------------- id
name      ------------- name

In the client application i link tables by the _id field, remotely i use the remote id field to fetch data, do joins, etc..

example locally:

Local Client Table       Local ClientType Table      Local ClientType
                         _id
                         remote_id
_id -------------------- client_id
remote_id                client_type_id -------------- _id
                                                      remote_id
name                    name                          name

example remotely:

Remote Client Table      Remote ClientType Table      Remote ClientType
id -------------------- client_id
                        client_type_id -------------- id
name                    name                          name

This scenario, and without any logical in the code, would cause data integrity failures, as the client_type table may not match the real id either in the local or remote tables, therefor whenever a remote_id is generated, it returns a signal to the client application asking to update the local _id field, this fires a previously created trigger in sqlite updating the affected tables.
http://www.sqlite.org/lang_createtrigger.html

1- remote_id is generated in the server

2- returns a signal to client

3- client updates its _id field and fires a trigger that updates local tables that join local _id

Of course i use also a last_updated field to help synchronizations and to avoid duplicated syncs.


问:
Storing data in elasticsearch vs mongodb
We are trying to create an online-shopping like application in which we have to store a huge amount of data,since the data that will be stored are mostly document like data, the suggestion was to store the data in mongodb and using elasticsearch to add the search functionality, but i also know that elasticsearch itself can be used as a database to store the data, but I'm not sure if that's the right thing to do.
Can you guys help me out?   </p>

答:
Elastic search is a search index that looks like a db and mongo is a database with decent search capabilities too.

I think the determinant should be your familiarity with the systems actually and if this is a greenfield project where you're diving into new technologies, you can minimize risk by using a more familiar technology like SQL instead of Mongo.

If you do go the mongo + elastic search route, my only other advice would be to NOT try to use the mongo db river, and insert and update into elastic search using the regular old rest api.


问:
How to migrate an XML serialization framework in Java in a tightly coupled system?
I work for a company that uses XML for storing a bunch of serialized Java classes. The framework we use is Apache Betwixt (abandonded in 2008) and it's kind of pain to maintain and extend (it seemed like a good choice back in the day).

Crash course in Betwixt along with the detailed problem:

Only supports public getters and setters, both getter and setter have to be present

Does not support JAXB-style type adapters

The XML evolves with the Java objects, resulting in redundant methods in our classes

Our list of xml serializable classes is well over 150, and the codebase can get very messy when changes to definitions are made. Since the XML is bound to Java getters and setters, we can only migrate XML by keeping old properties in the class definitions.

NowTake a look at this change:

```<code>public class ThingWithText {
  private String text;

  public String getText() {
     return text;
  }

  public void setText(String text) {
     this.text = text;
  }
}
</code>```

The resulting XML looks something like:

```<code><thingWithText>
    <text>Whatever</text>
</thingWithText>
</code>```

Now consider a change in the model to add multiple locales to the ThingWithText:

```<code>public class ThingWithText {
   private List<TextWithLanguage> texts = new LinkedList<TextWithLanguage>();

   // Getter must be here so the framework recognizes the property.
   public String getText() {
      return null;
   }

   // Has to be here so it can be serialized
   public void setText(String text) {
      this.texts.add(new TextWithLanguage(text));
   }

   public List<TextWithLanguage> getTexts() {
      return texts;
   }

   public void addText(TextWithLanguage text) {
      texts.add(text);
   }
}

public class TextWithLanguage {
   private Locale locale = // omitted;
   private String text;

   public TextWithLanguage(String text) {
      this.text = text;
   }

   // Getter and setter omitted
}
</code>```

The XML now looks like:

```<code><thingWithText>
    <texts>
        <text locale="en">Whatever</text>
    </texts>
</thingWithText>
</code>```

Now the XML isn't bad looking or anything, but it still leaves the ThingWithText class with several problems:

A setter for a non-existing field

A getter that always returns null, may cause exceptions because stuff still compiles

My questions go:

We have made the decision to do something about this, and it seems like a problem other people would have.

How does one handle migration between an old framework like Betwixt to a newer (JAXB, Xstream, whatever)?

If we were to keep our framework: How can we manage the considerable code complexity added by null methods and fake setters?

答:
How does one handle migration between an old framework like Betwixt to a newer (JAXB, Xstream, whatever)?

Make a new implementation for your data access layer.  If you don't have an explicit data access layer, this would be a good time to introduce one!  Stores will go to the new implementation, loads will come from either the new, if possible, or the old, if necessary.

```<code>dataaccess
  +-- betwixt
  +-- jaxb_xstream_whatever
</code>```

Some may argue that the whole DAO/DTO approach is ugly and leads to code bloat and duplication (I happen to be one of those people).  But I've often needed it, and it has saved projects large and old.

(Disclaimer: I had never heard of Betwixt before today, and had only a cursory look at the documentation.)

If we were to keep our framework: How can we manage the considerable code complexity added by null methods and fake setters?

Ideally, by changing the data so that it doesn't need them.  If you find yourself with a format change that is difficult to marry with a previous format, migrate all your data to the new format.  Your application already does this, piecewise, by supporting the previous format.  You're working with XML, so it may be as simple as a few XSL transformations.

If you can't migrate the data to a new format en masse, you can continue to support the previous format as long as you can make the getters and setters sensical (or at least deterministic), possibly deprecated methods.  Either make them useful, or make them throw exceptions: if setText does not throw an exception when I call it, I expect getText to return me a sensical result.

Lastly, if the format changed sufficiently that you cannot reliably support both formats in a single class, then either you're trying to shoehorn new concepts into old names, and you should really create a different data type, or the format represents a new generation of data types, and should supersede the previous class, with the previous clearly marked as such (ThingWithText_v1_8).

From what I gathered from a quick glance at the Betwixt documentation, they support creation chains and multiple mappings.  My guess is they could help you support multiple formats for as long as is really necessary, but I have no clue whether that would give something not-too-fragile.

Body:
How does one handle migration between an old framework like Betwixt to a newer (JAXB, Xstream, whatever)?

Make a new implementation for your data access layer.  If you don't have an explicit data access layer, this would be a good time to introduce one!  Stores will go to the new implementation, loads will come from either the new, if possible, or the old, if necessary.

dataaccess
  +-- betwixt
  +-- jaxb_xstream_whatever

Some may argue that the whole DAO/DTO approach is ugly and leads to code bloat and duplication (I happen to be one of those people).  But I've often needed it, and it has saved projects large and old.

(Disclaimer: I had never heard of Betwixt before today, and had only a cursory look at the documentation.)

If we were to keep our framework: How can we manage the considerable code complexity added by null methods and fake setters?

Ideally, by changing the data so that it doesn't need them.  If you find yourself with a format change that is difficult to marry with a previous format, migrate all your data to the new format.  Your application already does this, piecewise, by supporting the previous format.  You're working with XML, so it may be as simple as a few XSL transformations.

If you can't migrate the data to a new format en masse, you can continue to support the previous format as long as you can make the getters and setters sensical (or at least deterministic), possibly deprecated methods.  Either make them useful, or make them throw exceptions: if setText does not throw an exception when I call it, I expect getText to return me a sensical result.

Lastly, if the format changed sufficiently that you cannot reliably support both formats in a single class, then either you're trying to shoehorn new concepts into old names, and you should really create a different data type, or the format represents a new generation of data types, and should supersede the previous class, with the previous clearly marked as such (ThingWithText_v1_8).

From what I gathered from a quick glance at the Betwixt documentation, they support creation chains and multiple mappings.  My guess is they could help you support multiple formats for as long as is really necessary, but I have no clue whether that would give something not-too-fragile.