samedi 2 mars 2019

Design a robot application [on hold]

  • ROBOT APPLICATION

OBJECTIVE

  • Extensible – easily adaptable to future enhancements
  • Highly cohesive and loosely coupled
  • Good use of OOPS concepts
  • Make use of design pattern wherever possible
  • Code should be clean. Avoid code smells.
  • Can easily be unit tested. If possible, write unit tests

PROBLEM STATEMENT Time Duration: A company working in artificial intelligence domain is planning to create a Robot. But before they do heavy investment in Robot research and development, they requested their technical team to do a small prototype and create a Robot with some basic features.

Technical team decided to introduce following features in the Robot prototype:

Power Operated:

  1. Robot works on battery and can walk for 5 km per charge.
  2. If remaining battery is less than 15%, a red light on Robot head should lit up indicating low battery.

Handling physical objects:

  1. Robot can carry any object not weighing more than 10 Kg.
  2. For every Kilogram carried by Robot, 2% extra [in addition to walking discharge] battery will be consumed.
  3. If the weight of the object is more than 10 Kg, Robot display [LED display on chest] will show message “Overweight”.

Scanning:

  1. Robot can scan any bar code and display it's price on Robot Display.
  2. In case bar code is not clear enough for scanning, Robot display will show “Scan Failure”.

Technical team handed over these details to IT team to build a software for Robot.

Please help me to design and create a Robot application in Java for automating all the features listed above.

Following are acceptable assumptions:

  1. Display Message can be programmed as System.out.println.
  2. There is no need for creating bar code scanning functionality. We can assume that we already have an api which does that for us.

Getting rid of the `if` statements when creating dynamic subtypes

Its a question mainly about design.

Lets suppose we have a class that has the role of initiating different subclasses of a certain type by some parameters that it is iterating through. The problem comes when the __init__ method receives different parameter for each subtype. Is there any way to avoid the if statements inside the function that initializes the classes just to know what parameters to pass in? Maybe some design pattern that I am not aware of. Or is it an outcome of a bad design?

below is an example of what I mean. notice the manage static method that has the if...else... in it and if there were more types of workers, we would have more if's, which is what I am trying to avoid.

from abc import ABCMeta


class BaseWorker(metaclass=ABCMeta):
    def work(self):
        pass


class Worker1(BaseWorker):
    def __init__(self, name):
        self.name = name

    def work(self):
        pass


class Worker2(BaseWorker):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def work(self):
        pass


class Manager(object):
    @staticmethod
    def manage(attributes_list):
        for attributes in attributes_list:
            if "age" in attributes:
                w = Worker2(name=attributes["name"], age=attributes["age"])
            else:
                w = Worker1(name=attributes["name"])
            w.work()


if __name__ == '__main__':
    dynamic_attributes = [
        {"name": "davay"},
        {"name": "ok", "age": "55"},
        # and so on...
    ]
    Manager.manage(dynamic_attributes)


And the desired solution would have been

    @staticmethod
    def desired_manage(attributes_list):
        for attributes in attributes_list:
            w = worker_factory(attributes)
            w.work()

** Notice that the worker_factory is just an arbitrary name for the way that will solve this issue, it doesn't mean that factory pattern is the way to go. Even less, if we try factory pattern, from what I can see, the if statements will just move there and it wont solve anything.

Thanks!

Modeling Event and Reservations in JAVA Class - Best Design Approach

I am pretty new to java and am building a basic tour reservation system. I have a tour class which looks like this.

public class TourModel {
        
        private int tourID;
        private String tourname;
        private String tourlocation;
        private String country;
        private String groupsize;
        private String tourprice;
        private String tourduration;
        private String tourdescription;
        private int availableSeats;
        private Date tourDate;
        private String tourBanner;
        private ArrayList<ReservationModel> reservations;

The Reservation Class looks like

package com.artoftravel.pk.reservations;

import java.util.ArrayList; import java.util.Date;

public class ReservationModel {

private int reservationID;
private int tourID;
private int userID;
private String reservationstatus;
private int reservationpaymentstatus;
private int numberofattendees;
private Date reservationcreationdate;
private ReservationAttendees attendees;

Now in order to get all reservations based on a user ID I have a method in my DOA class that gets me all the reservations based on User ID field. however ,how can I also get all the tour info that the reservation is for?

Should I create another field in reservations model using the TourModel type? Wouldn't that be against the "HAS A" relationship (the reservation doesn't technically have a tour. it the other way around.

Maybe I'm overthinking this. but I wanted to ask for clarification since I'm not familiar with Object Oriented Design patterns.

public ArrayList<ReservationModel> getReservationByTourID(int tourID) {
                
                ArrayList<ReservationModel> reservations = new ArrayList<ReservationModel>();
                
                
                try {
                        Class.forName("com.mysql.cj.jdbc.Driver");

                        Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ArtofTravel", "root",
                                        "2001Space");
                        
                        String query = "select * from reservations where tour_ID = ?;";
                        PreparedStatement stmt = con.prepareStatement(query);
                        stmt.setInt(1, tourID);
                        
                        ResultSet rs = stmt.executeQuery();
                        
                        while (rs.next()) {
                                
                                reservations.add(new ReservationModel(rs.getInt("ID"), rs.getInt("tour_ID"),rs.getInt("user_ID"),rs.getString("reservation_Status"),rs.getInt("reservation_payment_status"),rs.getInt("number_of_attendees"), rs.getDate("reservation_create_date")));
                        
                        } 
                                stmt.close();
                                rs.close();
                                con.close();
                }       
                        catch (Exception e) {
                                e.printStackTrace();
                        }
                        
                        
                return reservations;
                
        }

Ideal architecture design for namespace parameters

I have 2 header files

a1.h

namespace a
{
  enum abc:uint8
  {
      abc1 = 1
      abc2 = 2
  };
}

and a2.h

namespace b
{
  enum abc:uint8
  {
      abc1 = 1
      abc2 = 2
      abc3 = 3
  };
}

I want to apply some operation dosomething(a::abc / b::abc) on the enum. The easiest solution would be to write two separate functions for different namespaces.

I am wondering if dosomething function can be templatized given 1. Enum values are same 2. Enum values are different. This would avoid code duplication and make the design extendable.

I have constraint that I cannot modify header files.

vendredi 1 mars 2019

How to Implement Factory Design Pattern for CsvProcessing based on Key

I have written a controller which is a default for MototuploadService(for Motor Upload), but I need to make one Factory Design so that based on parentPkId, need to call HealUploadService, TempUploadService, PersonalUploadService etc which will have separate file processing stages.

controller is below.

@RequestMapping(value = "/csvUpload", method = RequestMethod.POST)
    public List<String> csvUpload(@RequestParam String parentPkId, @RequestParam List<MultipartFile> files)
            throws IOException, InterruptedException, ExecutionException, TimeoutException {
        log.info("Entered method csvUpload() of DaoController.class");
        List<String> response = new ArrayList<String>();
        ExecutorService executor = Executors.newFixedThreadPool(10);
        CompletionService<String> compService = new ExecutorCompletionService<String>(executor);
        List< Future<String> > futureList = new ArrayList<Future<String>>();
        for (MultipartFile f : files) {
            compService.submit(new ProcessMutlipartFile(f ,parentPkId,uploadService));
            futureList.add(compService.take());
        }       
        for (Future<String> f : futureList) {
            long timeout = 0;
            System.out.println(f.get(timeout, TimeUnit.SECONDS));
            response.add(f.get());
        }
        executor.shutdown();
        return response;
    }

Here is ProcessMutlipartFile class which extends the callable interface, with CompletionService's compService.submit() invoke this class, which in turn executes call() method, which will process a file.

public class ProcessMutlipartFile implements Callable<String>
{
   private MultipartFile file; 
   private String temp;
   private MotorUploadService motUploadService;
   public ProcessMutlipartFile(MultipartFile file,String temp, MotorUploadService motUploadService )
   {
       this.file=file;
       this.temp=temp;
       this.motUploadService=motUploadService;
   }

   public String call() throws Exception 
   {

    return   motUploadService.csvUpload(temp, file);
    }

}

Below is MotorUploadService class, where I'm processing uploaded CSV file, line by line and then calling validateCsvData() method to validate Data, which returns ErrorObject having line number and Errors associated with it. if csvErrorRecords is null, then error-free and proceed with saving to Db. else save errorList to Db and return Upload Failure.

@Component
public class UploadService {

@Value("${external.resource.folder}")
     String resourceFolder;

    public String csvUpload(String parentPkId, MultipartFile file) {

    String OUT_PATH = resourceFolder;

    try {
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); 
            String filename = file.getOriginalFilename().split(".")[0] + df.format(new Date()) + file.getOriginalFilename().split(".")[1];
            Path  path = Paths.get(OUT_PATH,fileName)
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
        }
        catch(IOException e){
            e.printStackTrace();
            return "Failed to Upload File...try Again";
        }
        List<TxnMpMotSlaveRaw> txnMpMotSlvRawlist = new ArrayList<TxnMpMotSlaveRaw>();

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = "";
            int header = 0;
            int lineNum = 1;
            TxnMpSlaveErrorNew txnMpSlaveErrorNew = new TxnMpSlaveErrorNew();
            List<CSVErrorRecords> errList = new ArrayList<CSVErrorRecords>();
            while ((line = br.readLine()) != null) {
                // TO SKIP HEADER
                if (header == 0) {
                    header++;
                    continue;
                }
                lineNum++;
                header++;
                // Use Comma As Separator
                String[] csvDataSet = line.split(",");

                CSVErrorRecords csvErrorRecords = validateCsvData(lineNum, csvDataSet);
                System.out.println("Errors from csvErrorRecords is " + csvErrorRecords);

                if (csvErrorRecords.equals(null) || csvErrorRecords.getRecordNo() == 0) {
                    //Function to Save to Db

                } else {
                    // add to errList
                    continue;
                }
            }
            if (txnMpSlaveErrorNew.getErrRecord().size() == 0) {
                //save all
                return "Successfully Uploaded " + file.getOriginalFilename();   
            } 
            else {
                // save the error in db;
                return "Failure as it contains Faulty Information" + file.getOriginalFilename();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return "Failure Uploaded " + file.getOriginalFilename();
        }

    }

    private TxnMpMotSlaveRaw saveCsvData(String[] csvDataSet, String parentPkId) {
        /*
            Mapping csvDataSet to PoJo
            returning Mapped Pojo;
        */
    }

    private CSVErrorRecords validateCsvData(int lineNum, String[] csvDataSet) {
        /*
        Logic for Validation goes here
        */
    }

}

How to make it as a factory design pattern from controller, so that if

 parentPkId='Motor' call MotorUploadService,
    parentPkId='Heal' call HealUploadService 

I'm not so aware of the Factory Design pattern, please help me out. Thanks in advance.

Which design pattern shoud be used for creating a single database object?

I know I can use the singleton pattern but that's being called the anti-pattern because of testability and other reasons.

Having said that... which pattern should be used for creating a single database connection? Also, I've been searching the web and haven't found any answers. Can you tell me which search keywords you used to find the answer?

Suggestion to choose proper design pattern

I am asked to provide the documentation of a design for a "deal service" that de-couples the user’s requests from the requests to the partners who provide rental rates. the service does so, by looking up a cache, and fetching whatever is missing in a long-running process.

I am thinking about which design pattern would be appropriate for the software. I don't need to write working code, only the design documentation.

I am thinking about the combination of mediator and Flyweight design pattern.

The mediator pattern defines an object which encapsulates how a set of objects interacts. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. Rather than interacting directly with each other, objects ask the Mediator to interact on their behalf, which results in reusability and loose coupling.

On the other hand, The Flyweight Pattern is designed to control object creation where objects in an application have great similarities and are of a similar kind, and provides you with a basic caching mechanism. It allows you to create one object per type (the type here differs by a property of that object), and if you ask for an object with the same property (already created), it will return you the same object instead of creating a new one.

Do you have better suggestions?