Design pattern for 2 methods one has 70% arguments of other one

I am trying to do a design for notification part in the system I have 2 parts inApp notification and email notification so I used strategy pattern where I have interface NotificationSender with one single method send

NotificationSender{     public void send(A,B,C); } 

then I have 2 implmentations

InAppNotificationSender{     public void send(A,B,C){} } EmailNotificationSender{     public void send(A,B,C){} } 

later on, I had to increase parameters in the InAppNotificationSender so send should have D,E params as well which may change the design I thought of doing one single parameter for both methods using builder pattern something like

NotificationSender{         public void send(NotificationTemplateBuilder);     } 

What would be the good design to do such case

Design Pattern for object that asks questions of another object

I’m looking for a design pattern that might work for this class I am working with. This main class is an entity using Domain Driven Design.

   public class TimeCard() : ITimeCardHeader     {         public int TimeCardHeaderID { get; pivate set; }         public int ContractorID { get; internal set; }         public System.DateTime Date { get; internal set; }         public StateEnum State { get; protected internal set; }         public System.DateTime CreatedDate { get; internal set; }          public Update( ITimeCardHeader header)         {          //validation logic.          //assign values  e.g. This.ContractorID = header.ContractorID          // create and send domain event "Time card change"           }     } 

I would like to ask Questions(functions) of the timeCard object to determine if it could be edited. However, the business rule of if a timecard can be edited really is based on who you are.

So my Idea is to ask questions via an interface

interface IUser{  bool CanEditTimeCards{get;}  int? ContractorId {get;}  } 

Then I could have higher level classes Create a user then add methods to my TimeCard like.


My Question is where should that type of logic live. I had it directly on the Timecard object but I now think that it should be a class unto itself as it’s getting large.

Question: is there a design pattern that removes logic from a domain model that is exclusively used by that model to answer questions against it.

Design pattern example (Simple Window Explorer )

I want to know my code about Abstract Factory Pattern is near the principle? My exm is about Windows Explorer that when user run it , new form and other materials in form created .

Please look my code and know me about that.

Output :: Hello, world!           Form Created           Close button created            Minimize button created 

//Rextester.Program.Main is the entry point for your code. Don’t change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions;  namespace Rextester {     public class Program     {         public static void Main(string[] args)         {             //Your code goes here             Console.WriteLine("Hello, world!");              WindowsFactory formFactory=new Window();            WindowManager wm=new WindowManager(formFactory);             wm.RunForm();           }     }      abstract class WindowsFactory     {         public abstract Form CreateForm();         public abstract Button CreateCloseButton();         public abstract Button CreateMinimizebutton();      }    class Window:WindowsFactory    {        public override Form CreateForm()        {           return new XForm();        }        public override Button CreateCloseButton()        {            return new CloseButton();        }        public override Button CreateMinimizebutton()        {            return new MinimizeButton();        }    }    abstract class Form    {         public abstract void DrawForm();    }     class XForm:Form     {         public override void DrawForm()         {             Console.WriteLine("Form Created");         }     }      abstract class Button     {         public abstract void DrawCloseButton();         public abstract void DrawMinimizeButton();     }     class CloseButton:Button     {         public override void DrawCloseButton()         {             Console.WriteLine("Close button created");         }         public override void DrawMinimizeButton()         {          }     }     class MinimizeButton:Button     {         public override void DrawCloseButton()         {          }         public override void DrawMinimizeButton()         {             Console.WriteLine("Minimize button created");         }     }       class WindowManager     {         private Form _form;         private Button _closeButton;         private Button _minimizeButton;          public WindowManager(WindowsFactory factory)         {             _form=factory.CreateForm();             _closeButton=factory.CreateCloseButton();             _minimizeButton=factory.CreateMinimizebutton();         }         public void RunForm()         {             _form.DrawForm();             _closeButton.DrawCloseButton();             _minimizeButton.DrawMinimizeButton();         }     }  } 

SameSite cookie attribute and Synchronizer Token Pattern

Recently most browser have added support to the SameSite cookie attribute to prevent CSRF attacks:

Question if it is supported should we implement Synchronizer Token Pattern to prevent CSRF attacks?

Will SameSite prevent at least same CSRF attacks as Synchronizer Token Pattern?

I do know that SameSite options are strict and lax and probably we will use the strict value.

Experimenting with a OOP design pattern in JavaScript

Initially, I was using the class syntax to structure my code. While it sure did feel nice to work with, I found it lacked some important functionalities, like private properties and interfaces. Things that I had found useful in other OOP languages like Java.

I understand JavaScript doesn’t have classes, I’m trying here to experiment with prototypes. So this thread belongs more to Prototypal Class Design (no documentation there…).

I’m going for a Factory Function design, here are some of the advantages of using such technique to construct a “class” in JavaScript:

  • the factory and its instances can enclose private variables. This solves the problem of not having actual private instance/static properties usually seen in OOP languages.

  • we have control over the object’s prototype allowing us to combine prototypes from different factories. This makes it possible to “extend” factories with more properties/methods or mix multiple prototypes together similar to how interfaces work in OOP languages.

  • we can keep a good structure for our factories, if we extend a factory with some methods, the instances coming from this new extended factory will remain as an instance of the initial factory. In other words, the opertator instanceof will still work.

I have implemented such design using a IIFE wrapping the actual factory function. Here’s the initial factory called Person, and below a factory called Singer which extends Person‘s factory.

const Person = (function() {    // private shared variables   let total = 0;   let average = 0;   const updateAverage = function() {     average = total / Person.count;   }    // public static attributes   Person.count = 0;   Person.prototype = {     sayHi() {       return `Hi, I'm $  {}`;     }   }    function Person(name, age) {      // private instance variables             // public instance attributes     const properties = {       name,       gapToAverage() {         return Math.abs(age - average);       }     }      // some logic     Person.count += 1;     total += age;     updateAverage();      // return the instance     return Object.create(       Object.create(Person.prototype),              // Person's prototype       Object.getOwnPropertyDescriptors(properties)  // Person's own public instance properties     );    }    // return the constructor   return Person;  })(); 
const Singer = (function() {    let songs = {};    const prototypeExtension = {     sing(song) {       return songs[song];     }   }    // extend Person's prototype   Singer.prototype = Object.create(     Person.prototype,     Object.getOwnPropertyDescriptors(prototypeExtension)   );    function Singer(name, age, songs) {      const properties = {       getSongTitles() {         return Object.keys(songs);       }     }      // return the instance     return Object.assign(       Object.create(Singer.prototype),  // Singer's prototype       Person(name, age),                // Person's public instance properties       properties                        // Singer's own public instance properties     );    }    // return the constructor   return Singer;  })(); 

This is considered the best approach to object-oriented programming in JavaScript. What do you think of this approach to OOP in JavaScript?

I know it’s possible to do the exact same thing with the class syntax by declaring variables and enclosing them inside the scope of the class’ constructor. Which is better though?

Here is the full code with an example:

// creating an instance of Person const person = Person('Nina', 32);  console.log(Object.keys(person)); console.log("person instanceof Person: ", person instanceof Person)   // creating an instance of Singer const singer = Singer('John', 20, {   'Little Bird Fly': 'blah' });  console.log(Object.keys(singer)); console.log("singer instanceof Person: ", singer instanceof Person) console.log("singer instanceof Singer: ", singer instanceof Singer)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script>const Person=(function(){let total=0;let average=0;const updateAverage=function(){average=total/Person.count} Person.count=0;Person.prototype={sayHi(){return `Hi, I'm $  {}`}} function Person(name,age){const properties={name,gapToAverage(){return Math.abs(age-average)}} Person.count+=1;total+=age;updateAverage();return Object.create(Object.create(Person.prototype),Object.getOwnPropertyDescriptors(properties))} return Person})();const Singer=(function(){let songs={};const prototypeExtension={sing(song){return songs[song]}} Singer.prototype=Object.create(Person.prototype,Object.getOwnPropertyDescriptors(prototypeExtension));function Singer(name,age,songs){const properties={getSongTitles(){return Object.keys(songs)}} return Object.assign(Object.create(Singer.prototype),Person(name,age),properties)} return Singer})()</script>

Design pattern for similar classes that require different implementations

There could be a common or best practice for this scenario, but I am unfamiliar with it. However, it could very easily be a matter of subjective opinion on how one wants to implement their classes. Either way I am hopefuly to get some opinion from the spectrum of class designers here.

I am currently working on a project that allows users to generate files for data visualization.

The library will support two file types that are formatted differently (binary and XML). Due to this, I am left with a dilemma on how I want to control class instantiation and API access:

  1. Create a separate class for each file type and visualization type
  2. Create a separate class for each visualization type and load with methods for each file type
  3. (Not demonstrated) The inverse of Option 2

Option 1:

class Base:     # Stuff class F1V1(Base):     # Methods specific to file and visualization type one class F1V2(Base):     # Methods specific to file type one and visualization type two class F1V3(Base):     # Methods specific to file type one and visualization type three class F2V1(Base):     # Same logic as before but for file type two class F2V2(Base):     # ... class F2V3(Base):     # ... 

Here a user of the library would call their direct class to perform operations specific to it without the need of setting keyword parameters to determine what it does (e.g. fv = F1V2())

What is great about this way is that its explicit, a user knows exactly what file and visualization type they are working with. But I think its cumbersome and not extensible in the event I want to add more file or visualization types; forcing me to write a new class for each possible combination.

Option 2:

class Base:     # Stuff class V1(Base):     def __init__(self, ftype_1=True)         self.ftype_1 = ftype_1     def write(self):         if self.ftype_1:             # Write method specific to file type one         # Write method specific to file type two     # Assume 3 methods for each operation     # One method such as `write()`     # One method for each of the file types class V2(Base):     # Same logic as before class V3(Base):     # ... 

What I don’t like about this method is that I now have to define multiple methods for each class that execute based upon keywords provided at construction (i.e. fv = V2(ftype_1=False)). Ideally, what I would like is to supply a keyword argument that then determines which of the methods should belong to that class. For example:

fv = V2() # Only contains methods to file type one operations fv = V2(ftype_1=False) # Only contains methods to file type two operations 

As shown, there is nothing that prevents the following:

fv = V2() # Set for file type one fv.write_ftype_2() # Will produce an invalid file type formatting 

I am not sure of a way where I can dynamically bind/remove methods based upon keyword arguments. It would be great if I could simply write all the methods for each file type within each visualization type, then remove methods that are not relevant to the class anymore. Im not sure if this is even advisable, I can already think of a scenario like so:

def write(self):     if self.ftype_1:         # Write method specific to file type one     elif self.type_2:         # ...     else:         # ... 

If I dynamically removed methods from a class based upon keyword arguments, what would the point of the conditions be if say the first one held?


So which is a common or best practice? Which can be improved? Or am I missing another way?

An ideal example would be (in my mind):

fv = Hexagons(ftype='.abc', flat=True, area=3) fv.insert(data) fv.write(data) # Specifically writes for file types of '.abc' 

I suppose I could make Hexagons() return a subclass via __new__ but I think that might be unclear as to what is happening. To call Hexagons() but receive a ABCHexagons object could lead to confusion when users inspect the code base.

A factory method is ideal for this, but that is simply class instantiation. But each visualization type may have a variety of different keyword parameters that may not apply to the others. Rather, my issue lies with how to define them in the code base which ultimately leads to solving how to expose them to users.

When not to use View Services in MVVM design pattern?

I’m using the MVVM design pattern in my application which is comprised of,

  • A Xamarin.IOs project (View Layer)
  • A Net Standard project (Common Layer)
  • A Xamarin.Android project (in the future) (View Layer)

In the Xamarin.IOs project, there’s a Delegate class (NotificationCenterDelegate extending UNUserNotificationCenterDelegate) which triggers a method (WillPresentNotification) on receiving a notification. This method should inform a ViewModel (BasePageViewModel) that the method was invoked. The BasePageViewModel is not injected to the Delegate class.

There’s a couple of approaches I can use here,

  1. Inject a ViewModel (ControlViewModel). Then invoke a method in the ViewModel from the WillPresentNotification method.

    public void WillPresentNotification(/* parameters */) {     ControlViewModel.UpdateCount(); } 

    In ControlViewModel I invoke an event that is captured and handled in BasePageViewModel

  2. Implement an Interface (IDelegateViewService) in the Delegate class that has an Event Handler. Trigger the event in the WillPresentNotification method.

    public class NotificationCenterDelegate : UNUserNotificationCenterDelegate, INotificationCenterDelegate {     public void WillPresentNotification(/* parameters */)     {         CountUpdated?.Invoke(this, null);     } }  public interface IDelegateViewService {     event EventHandler CountUpdated; } 

    Then capture handle the event in the BasePageViewModel.

I prefer the first approach as it doesn’t use an interface to invoke something in the ViewModel. Because as I feel using ViewServices reduces the ability of sharing code among different platforms. And I feel ViewServices should be only used if it’s the only approach available.

Can anyone comment on these two design approaches? I would like to get some theory involving why one is better than the other or why a completely different design is much better!

What does this pattern match when filtering strings for URLs

What exactly is this line for

preg_replace('#[^0-9a-z]+#i', '-', parent::filter($  string)) 

in the following method in \vendor\magento\framework\Filter\TranslitUrl.php:

public function filter($  string) {     $  string = preg_replace('#[^0-9a-z]+#i', '-', parent::filter($  string));     $  string = strtolower($  string);     $  string = trim($  string, '-');      return $  string; } 

The method is used to filter strings which will be used in URLs, and I know that line replaces some strings with - character. But I don’t fully understand what exactly this pattern #[^0-9a-z]+#i matches.

I will appreciate any hints.