jeudi 21 février 2019

is this way of call a function a bad practique?

I have the following code:

public void moveCameraTo(Location location){
        moveCameraTo(location.getLatitude(), location.getLongitude());
    }

    public void moveCameraTo(double latitude, double longitude){
        LatLng latLng = new LatLng(latitude, longitude);
        moveCameraTo(latLng);
    }

    public void moveCameraTo(LatLng latLng){
        GoogleMap googleMap =  getGoogleMap();
        cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, INITIAL_MAP_ZOOM_LEVEL);
        googleMap.moveCamera(cameraUpdate);
    }

I think that with this way I eliminate the responsibility to know what is a LatLng in another class for example.

What do you think?

Android Studio Layout Design editor problem

Android Studio layout preview

Layout design Editor is not responding. When I drag anything to the design layout it moves to the top left corner and on clicking it disappears.

enter image description here

<TextView
    android:id="@+id/textView"
    android:textColor="Solid White"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:text="@string/TextView"
    android:textSize="20sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

enter code here

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


</android.support.constraint.ConstraintLayout>

Decorator Pattern with ever changing interfaces

I have a use case where I have a Database interface vended by an external vendor let's say it looks like following:

interface Database{

   public Value get(Key key);

   public void put(Key key, Value value)

}

The vendor provides multiple implementations of this interface e.g. ActualDatabaseImpl, MockDatabaseImpl. My consumers want to consume DataBase interface but before calling some of the APIs they want to perform some additional work e.g Call client side rate limiter before making call. So rather than every consumer having to do the extra work of checking rateLimiter's limit, I thought of creating a decorated class which will abstract out the rate limit part and consumers can interact with DB without knowing the logic of RateLimiter. e.g.

class RateLimitedDatabase implements Database{

    private Database db;
    public RateLimitedDatabase(Database db) {this.db = db;}

    public Value get(Key key) { 
          Ratelimiter.waitOrNoop();
          return db.get(key);
    }

    public void put(Key key, Value value) {
         Ratelimiter.waitOrNoop();
         return db.put(key, value);
    }
} 

This works fine as long as the Database interface doesn't introduce new methods.But as soon as they start adding APIs that I don't really care about e.g. delete/getDBInfo/deleteDB etc problems start arising.

Whenever a new version of DB with newer methods is released my build for RateLimitedDatabase will break.One option is to implement the new methods in the decorated class on investigating the root cause for build failure but that's just an extra pain for developers. Is there any other way to deal with such cases since this seems to be a common problem when using Decorator pattern with an ever changing/extending interface?

NOTE: I can also think of building a reflection based solution but that seems to be an overkill/over-engineering for this particular problem.

Create instance from class using other class

So i came across this case, an already published application needed to change all of it's API's & Models.


Now i have created a generic tier to handle the requests and apis and almost mid way into implementing all the services, now i came across this problem, the previous defined models are used widely around the application of course and since its MVC , Massive View Controller. it is going to cost me too much changing everything in each scene to the new model type,
therefore i thought of making an adapter to cast the new models when i get them in my callback closure to the old ones type.


I have already figured out a way but the problem its pretty much long, long way i am looking for a better approach if existed and a better solution over all for the case if there was a better one.


protocol Parsable {
    var time: String { get }
    var span: String { get }
    init(_ copy: Parsable)
}

class Foo: Parsable {
    required init(_ copy: Parsable) {
        self.span =  copy.span
        self.time =  copy.time
    }

    init(time: String, span: String) {
        self.time = time
        self.span = span
    }
    var time = ""
    var span = ""
}

class Fee: Parsable {
    required init(_ copy: Parsable) {
        self.span =  copy.span
        self.time = copy.time
    }
    init(time: String, span: String, date: String) {
        self.time = time
        self.span = span
        self.date = date // an extra var that is not used in Foo
    }
    var time = ""
    var span = ""
    var date = ""
}

var foo = Foo(time: "", span: "")
var fee = Fee(time: "2", span: "ye", date: "123")
// Usage
var deeped = Foo(fee)


As you can tell from the code i've created a protocol that contains the variables and an init() that holds its type, now imagine this to implement a model with +50 variable and +40 model in total, might need an age or two.

Create interface using Generics with different parameters in Java

I am building a rest service for file uploading and I have different file upload options as different controller methods.

This is my controller FileUploadController:

@RestController
public class FileUploadController {
    private static final String PATH_SEPARATOR = "/";
    private final FileUploadToS3Service fileUploadToS3Service;

    @Autowired
    public FileUploadController(FileUploadToS3Service fileUploadToS3Service) {
        this.fileUploadToS3Service = fileUploadToS3Service;
    }

    @GetMapping("/file-upload-to-s3")
    @ResponseBody
    public UploadResult uploadFileToS3Bucket(@Valid @RequestBody FileUploadToS3BucketRequest request) {
        return fileUploadToS3Service.uploadFileToS3Bucket(request.getBucketName(), request.getPathToUpload(), request.getFile());
    }

    @GetMapping("/file-url-upload-to-s3")
    @ResponseBody
    public UploadResult uploadFileFromUrlToS3Bucket(@Valid @RequestBody FileUrlUploadToS3BucketRequest request) {
        return fileUploadToS3Service.uploadFileUrlToS3Bucket(request.getBucketName(), request.getPathToUpload(), request.getFileUrl());
    }
}

This is FileUploadToS3Service interface:

public interface FileUploadToS3Service {
    UploadResult uploadFileToS3Bucket(String bucketName, String pathToUpload, File fileToUpload);

    UploadResult uploadFileUrlToS3Bucket(String bucketName, String pathToUpload, String fileUrlToUpload);
}

This is the service implementation FileUploadToS3ServiceImpl:

public interface FileUploadToS3Service {
    UploadResult uploadFileToS3Bucket(String bucketName, String pathToUpload, File fileToUpload);

    UploadResult uploadFileUrlToS3Bucket(String bucketName, String pathToUpload, String fileUrlToUpload);
}

My question is about making this service more generic to be make it extendable easily in the future. In the most basic approach I will create another interface and another implementation likes FileUploadToAnotherService and FileUploadToAnotherServiceImpl if another uploading api is integrated and the methods will have different parameters.

I assume that the clients will use the same methods with different upload locations. I thought about creating a common interface for these lets say FileUploadService instead of FileUploadToS3 interface and implement this for each different type of uploading strategy. However, I could not figure out how I will implement the methods with different parameters.

Looking forward to your helps. Thanks!

How to hide an interface in another interface?

I want to write an Android library, which in turn uses another Androd library.

Let's say I want to write libHigh which uses another libLow

There is an interface in libLow:

interface LowLevelInterface{ fun methodA() }

and I implement this in my higher level library libHigh:

open class OpenClassImpl : LowLevelInterface { override fun methodA(){//..} }

It is an 'open' class, because later in app layer I expect to extend from OpenClassImpl. But I dont want to make the interface 'LowLevelInterface' visible for later upper app level usage.

How can I hide the interface from libLow for the upper app level?

ASP.NET C# Code optimization to make it generic

I have a root Web API project and some other side class library projects where other apicontrollers are defined ( each project is a seperated webservice for external communications ).

Each side project has its own controller which has a BuildModel function where we do the mapping between the external webservice models and the models used internal.

Example of the BuildModel:

        // Get AX Customer
        OrderRequest order = ....
        var customer = order.Customer;
        var axCustomer =
            _customerService.GetCustomer(
                _mapper.Map<Customer, AxCustComSetup>(customer)
            );

        // Vendor
        var vendor = new AxVendor() { AccountNum = "11111", Name = "VENDOR" };

        // Get AX Articles
        var articles = _mapper.Map<IEnumerable<OrderLine>, IEnumerable<AxComArticle>>(order.Order.OrderLines);
        articles = _articleService.GetArticles(
            _mapper.Map(vendor, articles).ToList()
        );

        // Create EDI Journal and return true if succeeded
        var ediJournal = _mapper.Map<AxCustomer, AxComEdiJournal>(axCustomer);
        _mapper.Map(vendor, ediJournal);
        _mapper.Map(order.Order, ediJournal);

        var ediJournalLines = _mapper.Map<IEnumerable<AxComArticle>,
            IEnumerable<AxComEdiJournalLine>>(articles);
        ediJournal.Lines = ediJournalLines.ToList();
        ediJournal.CreateDate = DateTime.Now;
        ediJournal.OrderId = string.Empty;
        ediJournal.Remark = string.Empty;

        return ediJournal;

Basically, we need to make a AxComEdiJournal object which is then used in operations with our database.

For each side project we almost have the same identical method except for the external model types which is used to do the mapping.

Can we make this more dynamic or generic because now I copy paste this into other projects and change the model types.

For the mapping I use Automapper.