vendredi 2 octobre 2015

Dealing with legacy functions, how to prepare new interface which would adapt legacy functions

Use Case

  1. Assume that there is one Service Implemented in an multilayered .net app.

  2. Some ViewModels use this Service since it exposes functions they requires.

  3. This application has also possibility to run scripts executed by old legacy ScriptEngine (details are not imporant here).

  4. Above LegacyScriptEngine uses our Service

  5. Recently I added IronPython Engine to my application and would like to expose same functions as my old engine exposed.

  6. I was wondering how to prepare it to accomplish clean code.
  7. My solution should be flexible, e.g. in case another ScriptEngine used it could be used too.

    public class LegacyScriptEngine { Service _service;

    public LegacyScriptEngine(Service service)
    {
       _service = service;
    }
    
    Func1(int param)
    {
        _servcie.SomeFunc(param)
    }
    
    Func2(int param1, int param2, int param3, int param4)
    {
        //collect params and create someObject
        _servcie.SomeFunc(someObject);
    }
    
    //more functions...
    
    

    }

    public class PythonEngine { //Exposing same functions as old engine does PythonEngine(BigService servcie) { _mainScope.SetVariable("host_legacy", servcie); }
    }

Conclusions:

  • In my opinion IronPython engine should not know anything about LegacyEngine at all.
  • I should not expose my whole service since I would like use has only access to same functions as old engine allowed in order to cusomers could easily convert old scripts into new ones.
  • I thought to prepare an interface with same functions heading as old legacy service uses. e.g:

    public inteface LegacyFunctions { Func1(int someparams) { servcie.SomeFunc(someparams); }

    Func2(int param1, int param2, int param3, int param4)
    {
        //collect params and create someObject
        _servcie.SomeFunc(someObject);
    }
    
    

    }

  • Then I could prepare some Adapter which implements my interface and exposes it to python.

    public class ServcieToLegacyFunctionsAdapter
    {
        ServcieToLegacyFunctionsAdapter(BigService servcie)
        {
            _servcie = servcie;
        }
    
        Func1(someparams)
        {
            servcie.SomeFunc(someparams);
        }
    
        Func2(int param1, int param2, int param3, int param4)
        {
            //collect params and create someObject
            _servcie.SomeFunc(someObject);
        }
    }
    
    

What do you think about such solution, do you have any conclusions?

Celery task check application environment before run

In my application I have celery task that make subprocess call to external bin (may be not installed).

My task acts as follow:

class MyTask(app.Task):

    def __init__(self):
       try:
           do_some_check_on_the_ext_bin()
       except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            raise EnvironmentError
    def run(self, **kw):
       do_the_job_and_call_the_bin()

But I wonder if it the best way to do, to put the environment check in the init method ?

Notification or Delegate

I am stuck somewhere in message passing. Below is my scenario.

Please help me in writing a protocol with the help of which i can communicate between view controllers.

With reference to attached picture my Container view wants to communicate with View controller one, two, three and four but one at a time.

I have implemented notification but it seems to be a bad idea to me.

Please help me in implementing it in a correct way.

Thank you in anticipation Ankush

enter image description here

jeudi 1 octobre 2015

right approach setting up reusable context menus in pyqt/pyside

I am trying to implement menu in a way that I can reuse menu created for different widget however I can't think of how to get it working. I have read in book Design Patterns that

we should parameterize MenuItems with an object and not a function

how can I achieve this in python so that I can reuse some menu items at some widgets

For example I have this QMenu class:

from PyQt4.QtGui import QMenu

class MenuBase(QMenu):
    """docstring for MenuBase"""
    def __init__(self, ui):
        super(MenuBase, self).__init__()
        self._ui = ui
        self.getCommonMenus()

    @property
    def getshareMenu(self):
        self.shareMenu = QMenu('Share', self)
        self.shareMenu.addAction("Email")
        self.shareMenu.addAction("Dropbox")
        self.shareMenu.addAction("OneDrive")
        self.shareMenu.addAction("Facebook")
        return self.shareMenu

    def getCommonMenus(self):
        self.addSeparator()
        self.addAction('Show &Disk Stats', self._ui._showDiskStatSlot)
        self.addAction('&Quit', self._ui.quitAction)

    @property
    def getShareBtnMenu(self):
        return self.getshareMenu

and I want to use above menus in ui below: enter image description here

Use of Adapter/Facade pattern to anticipate incompatible interfaces and complexity?

Adapter pattern is mentioned in Wikipedia to fix incompatibilities between an expected interface and an actual interface.

Facade pattern is said to obscure complex implementations and present a simplified API.

However, would these patterns be used even in the absence of these issues? Aka, to use these patterns prematurely in anticipation of future incompatibility and complexity?

I have encountered code where a wrapper class was implemented with an exact copy of the interface of the inner class - it had all the public methods of the original with the exact same parameters. The wrapper class and the inner class were also defined in the same assembly.

Like so:

public class ClassifierImplementation
{
    private Classifier classifier_;
    public Wrapper() { classifier_ = new Classifier(); }

    public int[] Classify(double[] values, int seed)
    {
        return classifier_.Classify(values, seed);
    }

    // And other more public methods
}

What would be the rationale behind such an implementation?

Is there a database design pattern name for reducing duplicate join table data?

I have two tables with a join table to allow a many-to-many relationship.

enter image description here

It's a very familiar design pattern. It indicates which Branches each Member has access to.

As the number of members and branches increases I end up with a lot of data in the join table that is duplicated across members. Members tend to have access to the same groups of Branches as other Members.

So I'm looking at normalizing my data by creating a MemberProfile table that is effectively immutable. And rather than creating MemberBranch records for every Member I check for a matching MemberProfile, use if it already exists, or create one if it doesn't:

The idea being if I have a million Members with only a hundred access profiles this will save me a lot of space in my database.

enter image description here

I'm happy that it all works and that the development effort is worth is.

My question is "Is this a standard database design pattern, and if so, what is it called?"

Prototype pattern: ensure clone is in a valid state

LogEvent represents information like log level, message, user, process name, ... Some of these properties' values require pretty much effort for generation, e. g. the process name. Those properties' generated values are usually not changed, BUT despite this fact it should be possible to change them.

I considered the prototype pattern starting with a protoype, whose generic properties are pre-allocated. The protoype stays the same object during the lifetime of the application, but its properties' values might change as described above. New LogEvent objects should use the current prototype's values, objects created before the change should continue using the old values, that means, referencing the prototype from the "real" LogEvent object is not an option.

However the "real" LogEvent requires some properties to be not null, whereas this requirement is not useful for the prototype. I would like to prevent invalid objects of LogEvent. However if I use usual protoype pattern I would have to add a constructor to create the prototype, but this constructor would not create a valid object and I want to avoid, that an invalid object (the prototype itself or a clone of it) is used accidentally.

I spent some time on searching a solution, but the approaches listed below are pretty ugly. I hope, that there is an elegant solution. Meanwhile I tend to option 3, because 1 and 2 do not seem to be clean.

General structure

public interface ILogEvent
{
    string PreAllocatedProperty1 { get; set; }
    string PreAllocatedProperty2 { get; set; }
    string IndividualProperty1 { get; set; }
    string IndividualProperty2 { get; set; }
}

Option 1

Pros - LogEventPrototype can not be used as ILogEvent. - properties do not have to be declared in multiple classes Cons - properties have to be mapped manually - static methods => interface for prototypes not possible

class LogEventPrototype
{
    public string PreAllocatedProperty1 { get; set; }
    public string PreAllocatedProperty2 { get; set; }
    public string IndividualProperty1 { get; set; }
    public string IndividualProperty2 { get; set; }
    public LogEventPrototype() { GeneratePreAllocatedProperties(); }

    private void GeneratePreAllocatedProperties()
    {
        // if you invoke the helper functions later again, 
        // they might return different results (e. g.: user identity, ...)
        PreAllocatedProperty1 = Helper.ComplexFunction();
        PreAllocatedProperty2 = Helper.AnotherComplexFunction();
    }
}

class LogEvent : LogEventPrototype, ILogEvent
{
    // just for creating the prototype, object will be in an INVALID state
    private LogEvent() : base() {}
    // object will be in a VALID state
    public LogEvent(string individualProperty2) : this()
    {
        if (individualProperty2 == null)
            throw new ArgumentNullException();

        IndividualProperty2 = individualProperty2;
    }
    public static LogEvent FromPrototype(LogEventPrototype prototype)
    {
        // clone manually
        return new LogEvent(prototype.IndividualProperty2)
            {
                IndividualProperty1 = prototype.IndividualProperty1,
                PreAllocatedProperty1 = prototype.PreAllocatedProperty1,
                PreAllocatedProperty2 = prototype.PreAllocatedProperty2
            };
    }
}

Option 2

Similar to option 1, but:

Pros

  • constructor of LogEventPrototype is protected
  • it is "ensured", that LogEventPrototype is never instantiated, it is just used as return type
  • no manual mapping

Cons: It seems to be hacky.

class LogEventPrototype
{
    // properties ... (same as in option 1)
    protected LogEventPrototype() 
    {
        GeneratePreAllocatedProperties();
    }
}
class LogEvent : LogEventPrototype, ILogEvent
{
    // constructors same as in option 1; FromPrototype() removed
    public static LogEventPrototype CreateProtoype()
    {
        return new LogEvent();
    }
    public static LogEvent FromPrototype(LogEventPrototype prototype)
    {
        if(prototype.IndividualProperty2 == null)
            throw new ArgumentException();
        return (LogEvent)prototype;

    }
    public static LogEventPrototype CreateProtoype()
    {
        return new LogEvent();
    }
}

Option 3

Do not use a dedicated class for prototypes, but make the LogEvent constructor public and risk invalid LogEvent objects. Use a Validate() method instead and hope, that a client does not forget to use it.