java - Imperative to OOP Style - Snippet -


what best way make snippet more object oriented?

public class formatter {      private service service;      public formatter(service service) {         this.service = service;     }      public string dothejob(string theinput) {         string response = service.askforpermission();         switch (response) {         case "fail":             return "error";         case "ok":             return string.format("%s%s", theinput, theinput);         default:             return null;         }     } } 

if code doesn't need more complicated, shouldn't change anything.

but if write example of principle think it's example use "factory/delegation" pattern. principle create class children class cases. register every cases , use method choose class use response. method don't have use switch/case "not object oriented" purists.

your code following principle (be careful it's code illustrate principle):

abstract class job {     public abstract string dothejob(string theinput); }  class failjob extends job {     public string dothejob(string theinput) {         return "error";     } }  class okjob extends job {     public string dothejob(string theinput) {         return string.format("%s%s", theinput, theinput);     } }  class nulljob extends job {     public string dothejob(string theinput) {         return null;     } }   class formatter {     private service service;     private map<string, job> jobs;      public formatter(service service) {         this.service = service;          // init jobs         jobs = new hashmap<string, job>();         jobs.put("fail", new failjob());         jobs.put("ok", new okjob());     }      public string dothejob(string theinput) {         string response = service.askforpermission();         job job = getthejob(response);         return job.dothejob(theinput);     }      private job getthejob(string response) {         job job = jobs.get(response);         if(job == null) {             job = new nulljob();         }          return job;     } } 

but, once again, if code have do, stuck it, it's way simpler.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -