Magento 2 – What should repository methods return?

This question has been on my mind for some time. I’m currently writing a repository with the usual methods: save, getById, getList, delete and deleteById. What is the correct return for each method?

Repository::save($  dto)  - should the method return **$  this**, **$  dto** or (true || false)? 
Repository::getById(int $  id) - for this one I'm pretty sure that it should return the corresponding DTO 
Repository::getList(\Magento\Framework\Api\SearchCriteriaInterface $  searchCriteria)  - should the method (always) return \Magento\Framework\Api\SearchResults $  searchResult 
Repository::delete($  dto)  - should the method return **$  this** or (true or false)?  
Repository::deleteById(int $  id)  - should the method return **$  this** or (true or false)? 

Payment Methods Missing at Checkout

I had my site configured to accept payments from PayPal, Amazon, and Authorized net. Everything was working great. Last week, I upgraded to Magento 2.3.1 and installed Affirm as a payment method. I tried switching to a basic Magento theme to see if it was a bug in the theme, but it has the same issue.

After that, Affirm is the only payment option.

affirm only

As far as I can tell, these other payment options are still enabled.

Eg. Here is the amazon setting. The creds were still there. Login with amazon is working. enter image description here

I tried flushing the caches, I’ve tried recompiling the site. Still no dice.

Any suggestions?

What methods exist to damage or destroy worn or carried objects?

Most spells/abilities only allow the targeting of creatures rather than objects.

Of the few that do allow object targeting, most explicitly except “worn or carried” objects.

It ignites flammable objects in the area that aren’t being worn or carried. (Fireball)


A nonmagical object that isn’t being worn or carried also takes the damage if it’s in the spell’s area. (Shatter)

What methods do exist to damage or destroy objects that are worn or carried?

I’m looking for spells, abilities, items, or monsters that could achieve this.

using super-constructor vs methods polymorphism

I’m using Java but this applies to any OOP language. What is preferred between these two approaches?

First approach:

public abstract class Planet {   public abstract Colors[] getColors();   public abstract long getWeight();   public abstract int getIdFromEarth();   public abstract boolean isHabitable(); }  public class Earth extends Planet() {   public Color[] getColors() {     return Arrays.of(Color.BLUE, Color.GREEN);   }   public long getWeight() {     return 33338838383;   }   public int getIdFromEarth() {     return 3;   }   public boolean isHabitable() {     return true;   } } 

Second approach:

public abstract class Planet {   private final Colors[] colors;   private final long weight;   private final int idFromEarth;   private final boolean isHabitable;   public Planet(Colors[] colors, long weight, int idFromEarth, boolean isHabitable) {     this.colors = colors;     this.weight = weight;     this.idFromEarth = idFromEarth;     this.isHabitable = isHabitable;   }   public final Colors[] getColors() {     return colors;   }   public final long getWeight() {     return weight;   }   public final int getIdFromEarth() {     return idFromEarth;   }   public final boolean isHabitable() {     return isHabitable;   } }  public class Earth extends Planet() {     public Earth() {         super(Arrays.of(Color.BLUE, Color.GREEN),         33338838383,         3,         true)     } } 

I like second approach because:

  • subclasses are small (good if we have a lot of subclasses
  • no polymorphism involved (faster? more efficient?)

Cons of second approach in constructor call itself. It’s hard to say without IDE support which parameters are assinged and so easy to make I mistake:

        super(Arrays.of(Color.BLUE, Color.GREEN),         33338838383,         3,         true) 

Should I definitely prefer one of these approaches or may be you can suggest something else? Imaging we have more parameters – not 4, but 6 or 10. I don’t want to use enum cause in real app things a little more complicated and I have to have class hierarchy to operate with certain “group of planets”.

How to unit test methods which using static methods?

Let’s assume I wrote an extension method in c# for byte arrays which encodes them into hex strings, as follows:

public static class Extensions {     public static string ToHex(this byte[] binary)     {         const string chars = "0123456789abcdef";         var resultBuilder = new StringBuilder();         foreach(var b in binary)         {             resultBuilder.Append(chars[(b >> 4) & 0xf]).Append(chars[b & 0xf]);         }         return resultBuilder.ToString();     } } 

I could test the method above using nunit as follows:

[Test] public void TestToHex_Works() {     var bytes = new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };     Assert.AreEqual("0123456789abcdef", bytes.ToHex()); } 

If I use the Extensions.ToHex inside my project, let’s assume in Foo.Do method as follows:

public class Foo {     public bool Do(byte[] payload)     {         var data = "ES=" + payload.ToHex() + "ff";         // ...         return data.Length > 5;     }     // ... } 

Then all tests of Foo.Do will depend on the success of TestToHex_Works.

Using free functions in c++ the outcome will be the same: tests that test methods that use free functions will depend on the success of free function tests.

How can I handle such situations? Can I somehow resolve these test dependencies? Is there a better way to test the code snippets above?

Design Pattern to use when you want apply some common functionality to some specific methods?

I am trying to figure out a design pattern to use(if any exists) to a situation where I would be re-doing some functionality across a bunch of classes. Below is a (simplified) overview of the problem I am facing:

I have some Java code to CREATE, UPDATE, DELETE Student objects, Professor object, & Staff objects. And every time such object is either created, deleted, or updated, I want to extract some information about the affected object(such as name, age, id) and notify an external service. So something like:

class StudentDAO {    public Student createStudent(Student studentToCreate) {        jdbcTemplate.update(INSERT_SQL, .....);        //===> extract some info of the student        //let external service know a student was created....    }    public Student deleteStudent(Student studentToDelete) {        jdbcTemplate.update(DELETE_SQL, .....);        //===> extract some info of the student        //let external service know a student was deleted....    }    //same thing for update }  class ProfessortDAO {    public Professor createProfessor(Professor professorToCreate) {        jdbcTemplate.update(INSERT_SQL, .....);        //===> extract some info of the professor        //let external service know a Professor was created....    }    public Student deleteProfessor(Professor professorToDelete) {        jdbcTemplate.update(DELETE_SQL, .....);        //===> extract some info of the professor        //let external service know a professor was deleted....    }    //same thing for update }  //repeat for Staff 

The example is bit contrived but assume that Student, Professor, Staff share no inheritance hierarchy. Is there a way to achieve this functionality without copying and pasting the logic for extracting the info and sending it in all the DAO classes for CREATE, DELETE, UPDATE methods ?

How to improve a pattern ‘enum class with methods’

Over many years, I always find myself reconsidering this design, so I wanted to get some feedback on my solution to it.


I need a limited amount of objects = instances from a class, and I don’t want to expose the option to create more. I also want easy access to them from everywhere, and operators like equal / not equal.
They need to be class instances, as they need to have methods, so a enum doesn’t work.

(Simplified) Example:

Consider for example any chess-like game.

  1. There are three tile colors for the board needed, Lighter and Darker, and a different size tile where taken pieces are put. Also,
  2. the pieces have a color, typically White or Black; and I use NoColor for empty fields.

Both examples, each instance should know how to draw and serialize itself.

Obvious Option:

If I make a simple enum, the values cannot carry methods, so I end up with Draw and Serialize methods in some other class, which are basically an ugly switch/case.

My Solution:

I like to

  1. protect the constructor, and,
  2. create (public) static instances inside the class (C++17 now allows that even directly with inline).

‘Each instance gets created with a const ‘type’ in it (basically a enum), set through the constructor.
Wherever I need the information, I use the const pointer to that static instance. This allows to easily _compare and assign them, and also allows calling their member functions as needed.
It even allows other games to derive from the class and add new static instances, for example, a three-player chess could add a Red instance inside a derived class. Because I hand around pointers to the base class everywhere, it is polymorphic, and the code doesn’t have to handle the new color special in any way…

class Color { protected:   Color(char c) : color{c} {} public:   void Serialize(Archive& ar) const { ar << color; }  private:   const char color;  public:  // the only instances ever to exists; handed around by pointer   inline const static Color NoColor{'X'};   // C++17 syntax, otherwise   inline const static Color White{'W'};     // separate line in .cpp needed   inline const static Color Black{'B'}; };  class Chess3Color : public Color { protected:   Chess3Color(char c) : Color{c} {}  public:   inline const static Chess3Color Red{'R'}; }; 

Example Usage:

... // create a White King Piece* p = new WhiteKing{&Type::King, &Color::White, IDB_W_K_BMP}; ... if (p->IsColor(&Color::White)) { ... } ... p->Serialize(ar); ... class Piece {   ...   // Piece member function for serialization   void Serialize(Archive& ar)   {     type->Serialize(ar);     color->Serialize(ar);   }   ...   // check if this piece is of a certain color   // note that pointer compare is good enough!   bool IsColor(const Color* c) { return color == c; }   ... } 


I go back and forth in my mind between this being a code smell or a pretty good and clean solution. So is it a code smell?
How else would this be better designed?

I have read a lot about Singletons, and I don’t think they would do me any good (aside from the fact that some people think they are a code smell too).

Using functional interface arguments in methods of services injected via Spring

Here is the working code for my Spring service:

@Service public class UploadService {      @Inject     @Qualifier("session")     Session session;      @Inject     AsyncImageConvertService asyncImageConvertService;      @Value("$  {aws.bucket-name}")     String awsBucketName;      @Inject     AmazonS3 amazonS3;      @Inject     ImageMapper imageMapper;      @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)     public void uploadImage(Image image, String url, Runnable fnSaveObject) {         File file = new File(System.getProperty(""), image.getUrl());          image.setUrl(url);         image.setCreator(session.getUser());         PutObjectRequest request = new PutObjectRequest(awsBucketName, image.getUrl(), file);         request.setCannedAcl(CannedAccessControlList.PublicRead);         amazonS3.putObject(request);          TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {             public void afterCommit() {                 asyncImageConvertService.processImage(image.getId(), file);             }         });          imageMapper.insert(image);;     } } 

It is called from the following code:

uploadService.uploadImage(                 profileImage,                 "/user/" + user.getId() + "/" + profileImage.getUrl(),                 () -> userMapper.insertImage(user, profileImage) ); 

The Runnable functional interface will run in transaction and invoke async service method after transaction committed.

*Mapper is injected instance also, via spring-mybatis.

This code looks like it’s working well, but I’m afraid it’s not safe.

Is it safe to use functional interface arguments in methods of services injected via Spring?

Force instance methods to use only public members

What do you think about code like this:

public class ThisClass {     // this method uses only public members     public void DoSomething()     {         AccessToPublicMembersOfThisClass.DoSomething(this);     } }  // EDIT: this class is not nested! internal class AccessToPublicMembersOfThisClass {     internal void static DoSomething (ThisClass x)     {        // we are sure were using only public members because        // private members are unaccessible from here          x.Action();     } } 

Is it good or not?

I could do some static methods, but I don’t want to pass any arguments to them.