• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Ocena czystości kodu

Object Storage Arubacloud
0 głosów
301 wizyt
pytanie zadane 3 czerwca 2017 w JavaScript przez Sławek Obywatel (1,270 p.)

Cześć wszystkim, chciałbym się zapytać o rade co można zrobić w skrypcie javascript poniżej korzystającego z Google Map API, żeby był bardziej czytelny i wydajniejszy:)

class Geolocations
{

    constructor(radius_circle) {
        this.radius_circle = radius_circle;
    }

    init(options) {

        if(!options.location) return;

        try {google.maps.event.addDomListener(window, "load", this.makeMap.bind(this)); } catch(e) { return; }

        try {google.maps.event.addDomListener(window, "load", this.Listener.bind(this)); } catch(e) { return; }

        this.options = options;
        this.location = this.options.location;
    }

    makeMap() {
        this.GetAllLocationsOnMap();

        var elements=0;
        this.elements=elements;

        var TableTypeSelectedIcon=[];
        this.TableTypeSelectedIcon=TableTypeSelectedIcon;

        var TableIfIconSelect=[];
        this.TableIfIconSelect=TableIfIconSelect;
        
        var geokoder = new google.maps.Geocoder();
        this.geokoder=geokoder;
        
        var loc = this.location.split(","),
            pos = new google.maps.LatLng(loc[0], loc[1]);

        var mapOptions =new google.maps.Map(document.querySelector("#map"), {
            zoom: 13,
            center: pos,
            disableDefaultUI: false,
            scaleControl: true,
            zoomControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            streetViewControl:false,
            mapTypeControl: true,
            mapTypeControlOptions:
            {
                position: google.maps.ControlPosition.BOTTOM_LEFT 
            }
        });

        this.mapOptions=mapOptions;
        var Map = new google.maps.Map(document.getElementById("map"), mapOptions);  
        this.Map=Map;

    }

    GetAllLocationsOnMap(val)
    {
      var lan="http://localhost:3000/api/connectAll/";

      this.SendRequestToDatabase(lan);
    }

    Listener(){
      var markers_on_map = [];
      this.markers_on_map=markers_on_map;
       
      var Circle=()=>this.circle;
      var CallbackToThisDragListener=()=>this.DragListener();

        google.maps.event.addListener(this.Map,'dragstart',function(zdarzenie)
        {  

                Circle().setMap(null);
            
        });

        google.maps.event.addListener(this.Map,'dragend',function(zdarzenie)
        {    

                for (var i = 0; i < markers_on_map.length; i++) {
                  if (markers_on_map[i]) {
                    markers_on_map[i].setMap(null);
                    markers_on_map[i] = null;
                  }
                }

              CallbackToThisDragListener();

        });
    }

    DragListener()
    {
      this.CheckAddressValue();
    }

    CheckAddressValue()
    {
      
      var CallbackToThisCreateCircle=()=>this.CreateCircle();
      var CallbackToThisAll_locations=this.BringDataFromDatabase.locations;
      var CallbackUpdateMarker=(All_locations,iteration)=>this.SaveGlobalLocationsValueInClass(All_locations,iteration);

      if(this.address==null)
      {
        this.address='';
      }

      if (this.geokoder) {
        
       this.geokoder.geocode({'address': this.address}, function (results, status) {
                    
         if (status == google.maps.GeocoderStatus.OK) {

            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

                    CallbackToThisCreateCircle();

                    for (var iteration = 0; iteration < CallbackToThisAll_locations.length; iteration++) {


                            CallbackUpdateMarker(CallbackToThisAll_locations[iteration],iteration);

                    }
                  }     
                } 
              });
            }
    }

    CreateCircle()
    {
       var mylat=this.Map.getCenter().lat();
       this.mylat=mylat;
       var mylng=this.Map.getCenter().lng();
       this.mylng=mylng;

       var circle;  

        circle = new google.maps.Circle({
          map: this.Map,
          position: new google.maps.LatLng(mylat, mylng),
          radius: this.radius_circle,    
          strokeColor: '#b2dae8',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          clickable: false,
          fillColor: '#b2dae8',
          fillOpacity: 0.35
        });

        this.circle=circle;

        circle.bindTo('center', circle, 'position');
    }

    SaveGlobalLocationsValueInClass(LocationsOnMap,iteration)
    {
      this.LocationsOnMap=LocationsOnMap;
      this.iteration=iteration;
      this.SetMarkerLocation(iteration)
    }

    SetMarkerLocation()
    {
      var DymekLocations=this.LocationsOnMap;

      var Mapka=()=>this.Map;

      var InfoWindow = new google.maps.InfoWindow();

      var wartosc=this.ComputeDistance();
      var marker_lat_lng=wartosc[0];
      var distance_from_location=wartosc[1];


      if (distance_from_location <= this.radius_circle) {

          var new_marker=this.CreatNewMarker(marker_lat_lng);
          this.new_marker=new_marker;

          this.FiltersMarkers();

          google.maps.event.addListener(new_marker, 'mouseover', function () {

            InfoWindow = new google.maps.InfoWindow({ 
              content: '<div style="color:black"><strong>'+DymekLocations.name+'</strong><br>'+DymekLocations.street+'<br>'+DymekLocations.phone+'</div>',
              size: new google.maps.Size(150,50),
              pixelOffset: new google.maps.Size(0, -30),
              position: marker_lat_lng,
              map: Mapka()
            });
              google.maps.event.addListener(new_marker, 'mouseout', function () {
                if(InfoWindow){
                                
                   InfoWindow.setMap(null);
                   InfoWindow = null;
                }

              });
          });

        this.markers_on_map.push(new_marker);

      }
      
    }

     ComputeDistance()
    {
      var marker_lat_lng = new google.maps.LatLng(this.LocationsOnMap.lat, this.LocationsOnMap.lng);

      var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(this.mylat, this.mylng), marker_lat_lng); 

      return [marker_lat_lng, distance_from_location];

    }

     CreatNewMarker(marker_lat_lng)
    {
      var new_marker = new google.maps.Marker({
          position: marker_lat_lng,
          map: this.Map,
          title: location.name
      });

        return new_marker;

    }

    FiltersMarkers()
    {

            if(this.BringDataFromDatabase.locations[this.iteration].type.indexOf(this.address) != -1
              || this.BringDataFromDatabase.locations[this.iteration].name.indexOf(this.address) != -1
              ||this.BringDataFromDatabase.locations[this.iteration].name==this.address 
              || this.BringDataFromDatabase.locations[this.iteration].type==this.address)
            {

                  this.new_marker.setVisible(true); 

            }
            else
            {
                  this.new_marker.setVisible(false);
            }      


            this.FiltersMarkersOnTypeSelectedIcon();
                          
    }

    FiltersMarkersOnTypeSelectedIcon()
    {
      for(var x=0;x<this.TableTypeSelectedIcon.length;x++)
      {
        if(this.TableIfIconSelect[x]==true && this.BringDataFromDatabase.locations[this.iteration].type==this.TableTypeSelectedIcon[x])
        {
            this.new_marker.setVisible(false);   
        }
      }
            
    }   

    UpdateCircleRadius(rad) {
      this.radius_circle=rad;
      this.circle.radius=rad;

      this.circle.bindTo('center', this.circle, 'position');

      this.UpdateNumbersOfMarkers();

    }

    UpdateNumbersOfMarkers()
    {

      var All_locations=this.BringDataFromDatabase.locations;
      var CallbackUpdateMarker=(All_locations,iteration)=>this.SaveGlobalLocationsValueInClass(All_locations,iteration);

      this.CleanMarkersOnMap();

      for (var iteration = 0; iteration < All_locations.length; iteration++) {

        CallbackUpdateMarker(All_locations[iteration],iteration);

      }
    }

    UncheckedLocation(TypeSelectedIcon,IfIconSelect)
    { 

      if(this.TableTypeSelectedIcon.indexOf(TypeSelectedIcon)>-1)
      {
        var TheSameElementInArray=this.TableTypeSelectedIcon.indexOf(TypeSelectedIcon);

        this.TableIfIconSelect[TheSameElementInArray]=IfIconSelect;
      }
      else
      {

        this.TableTypeSelectedIcon[this.elements]=TypeSelectedIcon;

        this.TableIfIconSelect[this.elements]=IfIconSelect;

        this.elements=this.elements+1;
      }
      
      this.UpdateNumbersOfMarkers();
    }

    UpdateAddressValue(val)
    {
      this.circle.setMap(null);

      this.CleanMarkersOnMap();

      this.address=val;
      this.CheckAddressValue();
    }
    CleanMarkersOnMap(){

      for (var i = 0; i < this.markers_on_map.length; i++) {
        if (this.markers_on_map[i]) {
          this.markers_on_map[i].setMap(null);
          this.markers_on_map[i] = null;
        }
      }

    }
    SendRequestToDatabase(lan)
    {
      var SaveLocationsFromDatabaseArrowFunction=(BringDataFromDatabase)=>this.BringDataFromDatabase=BringDataFromDatabase;

      var xhr = new XMLHttpRequest();
      
      xhr.open("POST",lan);

      xhr.onreadystatechange = function(e)
      {

        if (this.readyState === 4 && this.status === 200) {
          
            var res=xhr.responseText;
            var BringDataFromDatabase=JSON.parse(res); 

            SaveLocationsFromDatabaseArrowFunction(BringDataFromDatabase);

        }
      };
      
      xhr.send(null);
    }

}


var geo=new Geolocations(3000);

geo.init({
    location: "51.269262, 22.548271",
});

function sliderChange(val) {
    
        var kolo=val*100;
        geo.UpdateCircleRadius(kolo);

}
function IconClick(TypeSelectedIcon,IfIconSelect) {

  geo.UncheckedLocation(TypeSelectedIcon,IfIconSelect);
    
}

var clearSearch;
var WaitForDataFromDatabase;

function InputSearchValue(val){
  
    clearTimeout(clearSearch);
    clearTimeout(WaitForDataFromDatabase);

    WaitForDataFromDatabase=setTimeout(()=>{

        var lan="http://localhost:3000/api/connect/"+val;
      
        geo.SendRequestToDatabase(lan);
      
    },500);

    clearSearch=setTimeout(()=>{

      geo.UpdateAddressValue(val);

    },600);
}

 

1 odpowiedź

+1 głos
odpowiedź 4 czerwca 2017 przez rafal.budzis Szeryf (85,260 p.)
wybrane 4 czerwca 2017 przez Sławek
 
Najlepsza

Spory ten kod i ma wiele błędów stylistycznych na moje oko ;)

1) przyjmuje się ze klasy nazywamy dużą literą a funkcje zaczynamy od małej. Klasa ma poprawna nazwę ale juz funkcje GetAllLocationsOnMap, Listener nie.

2) porozrzucane zmienne klasy (pola). Jeśli chcemy mieć czytelny kod na starcie w konstruktorze powinieneś utworzyć wszystkie pola. np w funckcji init tworzysz. this.options = options; w konstruktorze dodaj this.options = null; dzieki temu na starcie bedziemy znać wszystkie pola.

3) w metodzie makeMap masz nie potrzebne tworzenie zmiennych. 

        var TableIfIconSelect=[];
        this.TableIfIconSelect=TableIfIconSelect;

dlaczego nie zrobić tak ? ;)

        this.TableIfIconSelect=[];

ten sam błąd mamy też np w funkcji CreateCircle, Listener. 

4) w lepszy sposób można by odwołać się do mapy ponieważ raz odwołujesz się do document.querySelector("#map") potem używasz document.getElementById("map") trzeba sie na coś zdecydować :P. Najlepiej by było stworzyć w konstruktorze, this.mapDOMElement = document.getElementById("map"); i potem używać wszędzie pola this.mapDOMElement

5) z mojego doświadczenia wynika ze if bez klamer to najgorczy wróg czytelności kodu. Gdybym ja pisał ten kod w 10 linijce dodał był klamerki.

    init(options) {
 
        if(!options.location){
              return;
        }
    [...]

6) Odpowiednie komentarze do kodu też są nie ocenione gdy napiszemy je w jakimś standardzie. Polecam zapoznać się z JSDoc. Najważniejsze to opisać działanie funkcji i udokumentować parametry http://usejsdoc.org/tags-param.html oraz zwracaną wartość http://usejsdoc.org/tags-returns.html.

7) Warto by też sformatować kod w jednym standardzie czasem jest za dużo spaci czasem tabulatorów przy znaku = czasem obok nie ma spacji czasem jest z jednej strony czasem z dwóch stron warto by wprowadzić jeden standart którego bedziesz się trzymał

 

Jak skończysz daj znać i wrzuć poprawione coś sie pewnie jeszcze znajdzie ;)

komentarz 4 czerwca 2017 przez Sławek Obywatel (1,270 p.)
Wielkie dzięki, jak skończę na pewno dam znać:)

Podobne pytania

0 głosów
1 odpowiedź 368 wizyt
pytanie zadane 21 sierpnia 2017 w JavaScript przez Marchiew Dyskutant (7,690 p.)
+2 głosów
3 odpowiedzi 858 wizyt
pytanie zadane 9 lipca 2017 w JavaScript przez Ziken Początkujący (330 p.)
0 głosów
1 odpowiedź 246 wizyt
pytanie zadane 4 maja 2017 w JavaScript przez Radekol Bywalec (2,880 p.)

92,579 zapytań

141,429 odpowiedzi

319,657 komentarzy

61,962 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...