oop - Building one object given another -


say calling third-party api returns post, , want take , transfer properties own post class. have in past had method public static my.post build(their.post post) maps properties how want.

however, better/valid have constructor accepts their.post , property mapping in there? or should there separate class converting, , leaves my.post in more pojo state?

thanks thoughts!

these answers starts "it depends."

people argue against using public static methods, based on fact hard mock them (i don't buy bandwagon).

this comes down design, want post part of class? if add "copy" constructor part of class , dependent on changes post. if change post, code has adapt.

the better solution decouple it. need find extenal method map two. 1 way use static builder method (like mentioned) or if want take step further, more complicated solution extract information want post type of generic collection class. create constructor accept constructor class. way if change design class stays in tact , have update mappings post generic representation of it.

public class mypost{     public mypost(icollectionofproperties props){        //copy properties.       }  }  public static class theirpostextensions{    public static icollectionofproperties extractproperties(this theirpost thepost){          return new collectionofproperties(){                  = thepost.propa,                  b = thepost.propb          };    } }   public class example{    public example(){        theirpost tp = new theirpost();        icollectionofproperties  props = tp.extractproperties();        mypost mp = new mypost(props);    }  } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -