Search Results

Search found 1030 results on 42 pages for 'refactoring'.

Page 10/42 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Code refactoring homework?

    - by Hira
    This is the code that I have to refactor for my homework: if (state == TEXAS) { rate = TX_RATE; amt = base * TX_RATE; calc = 2 * basis(amt) + extra(amt) * 1.05; } else if ((state == OHIO) || (state == MAINE)) { rate = (state == OHIO) ? OH_RATE : MN_RATE; amt = base * rate; calc = 2 * basis(amt) + extra(amt) * 1.05; if (state == OHIO) points = 2; } else { rate = 1; amt = base; calc = 2 * basis(amt) + extra(amt) * 1.05; } I have done something like this if (state == TEXAS) { rate = TX_RATE; calculation(rate); } else if ((state == OHIO) || (state == MAINE)) { rate = (state == OHIO) ? OH_RATE : MN_RATE; calculation(rate); if (state == OHIO) points = 2; } else { rate = 1; calculation(rate); } function calculation(rate) { amt = base * rate; calc = 2 * basis(amt) + extra(amt) * 1.05; } How could I have done better? Edit i have done code edit amt = base * rate;

    Read the article

  • C#: AutoFixture refactoring

    - by Thomas Jaskula
    Hello, I started to use AutoFixture http://autofixture.codeplex.com/ as my unit tests was bloated with a lot of data setup. I was spending more time on seting up the data than to write my unit test. Here's an example of how my initial unit test looks like (example taken from cargo application sample from DDD blue book) [Test] public void should_create_instance_with_correct_ctor_parameters() { var carrierMovements = new List<CarrierMovement>(); var deparureUnLocode1 = new UnLocode("AB44D"); var departureLocation1 = new Location(deparureUnLocode1, "HAMBOURG"); var arrivalUnLocode1 = new UnLocode("XX44D"); var arrivalLocation1 = new Location(arrivalUnLocode1, "TUNIS"); var departureDate1 = new DateTime(2010, 3, 15); var arrivalDate1 = new DateTime(2010, 5, 12); var carrierMovement1 = new CarrierMovement(departureLocation1, arrivalLocation1, departureDate1, arrivalDate1); var deparureUnLocode2 = new UnLocode("CXRET"); var departureLocation2 = new Location(deparureUnLocode2, "GDANSK"); var arrivalUnLocode2 = new UnLocode("ZEZD4"); var arrivalLocation2 = new Location(arrivalUnLocode2, "LE HAVRE"); var departureDate2 = new DateTime(2010, 3, 18); var arrivalDate2 = new DateTime(2010, 3, 31); var carrierMovement2 = new CarrierMovement(departureLocation2, arrivalLocation2, departureDate2, arrivalDate2); carrierMovements.Add(carrierMovement1); carrierMovements.Add(carrierMovement2); new Schedule(carrierMovements).ShouldNotBeNull(); } Here's how I tried to refactor it with AutoFixture [Test] public void should_create_instance_with_correct_ctor_parameters_AutoFixture() { var fixture = new Fixture(); fixture.Register(() => new UnLocode(UnLocodeString())); var departureLoc = fixture.CreateAnonymous<Location>(); var arrivalLoc = fixture.CreateAnonymous<Location>(); var departureDateTime = fixture.CreateAnonymous<DateTime>(); var arrivalDateTime = fixture.CreateAnonymous<DateTime>(); fixture.Register<Location, Location, DateTime, DateTime, CarrierMovement>( (departure, arrival, departureTime, arrivalTime) => new CarrierMovement(departureLoc, arrivalLoc, departureDateTime, arrivalDateTime)); var carrierMovements = fixture.CreateMany<CarrierMovement>(50).ToList(); fixture.Register<List<CarrierMovement>, Schedule>((carrierM) => new Schedule(carrierMovements)); var schedule = fixture.CreateAnonymous<Schedule>(); schedule.ShouldNotBeNull(); } private static string UnLocodeString() { var stringBuilder = new StringBuilder(); for (int i = 0; i < 5; i++) stringBuilder.Append(GetRandomUpperCaseCharacter(i)); return stringBuilder.ToString(); } private static char GetRandomUpperCaseCharacter(int seed) { return ((char)((short)'A' + new Random(seed).Next(26))); } I would like to know if there's better way to refactor it. Would like to do it shorter and easier than that. Thanks in advance for your help.

    Read the article

  • AutoFixture refactoring

    - by Thomas Jaskula
    I started to use AutoFixture http://autofixture.codeplex.com/ as my unit tests was bloated with a lot of data setup. I was spending more time on seting up the data than to write my unit test. Here's an example of how my initial unit test looks like (example taken from cargo application sample from DDD blue book) [Test] public void should_create_instance_with_correct_ctor_parameters() { var carrierMovements = new List<CarrierMovement>(); var deparureUnLocode1 = new UnLocode("AB44D"); var departureLocation1 = new Location(deparureUnLocode1, "HAMBOURG"); var arrivalUnLocode1 = new UnLocode("XX44D"); var arrivalLocation1 = new Location(arrivalUnLocode1, "TUNIS"); var departureDate1 = new DateTime(2010, 3, 15); var arrivalDate1 = new DateTime(2010, 5, 12); var carrierMovement1 = new CarrierMovement(departureLocation1, arrivalLocation1, departureDate1, arrivalDate1); var deparureUnLocode2 = new UnLocode("CXRET"); var departureLocation2 = new Location(deparureUnLocode2, "GDANSK"); var arrivalUnLocode2 = new UnLocode("ZEZD4"); var arrivalLocation2 = new Location(arrivalUnLocode2, "LE HAVRE"); var departureDate2 = new DateTime(2010, 3, 18); var arrivalDate2 = new DateTime(2010, 3, 31); var carrierMovement2 = new CarrierMovement(departureLocation2, arrivalLocation2, departureDate2, arrivalDate2); carrierMovements.Add(carrierMovement1); carrierMovements.Add(carrierMovement2); new Schedule(carrierMovements).ShouldNotBeNull(); } Here's how I tried to refactor it with AutoFixture [Test] public void should_create_instance_with_correct_ctor_parameters_AutoFixture() { var fixture = new Fixture(); fixture.Register(() => new UnLocode(UnLocodeString())); var departureLoc = fixture.CreateAnonymous<Location>(); var arrivalLoc = fixture.CreateAnonymous<Location>(); var departureDateTime = fixture.CreateAnonymous<DateTime>(); var arrivalDateTime = fixture.CreateAnonymous<DateTime>(); fixture.Register<Location, Location, DateTime, DateTime, CarrierMovement>( (departure, arrival, departureTime, arrivalTime) => new CarrierMovement(departureLoc, arrivalLoc, departureDateTime, arrivalDateTime)); var carrierMovements = fixture.CreateMany<CarrierMovement>(50).ToList(); fixture.Register<List<CarrierMovement>, Schedule>((carrierM) => new Schedule(carrierMovements)); var schedule = fixture.CreateAnonymous<Schedule>(); schedule.ShouldNotBeNull(); } private static string UnLocodeString() { var stringBuilder = new StringBuilder(); for (int i = 0; i < 5; i++) stringBuilder.Append(GetRandomUpperCaseCharacter(i)); return stringBuilder.ToString(); } private static char GetRandomUpperCaseCharacter(int seed) { return ((char)((short)'A' + new Random(seed).Next(26))); } I would like to know if there's better way to refactor it. Would like to do it shorter and easier than that.

    Read the article

  • How to Extract Properties for Refactoring

    - by Ngu Soon Hui
    I have this property public List<PointK> LineList {get;set;} Where PointK consists of the following structure: string Mark{get;set;} double X{get;set;} doible Y{get;set;} Now, I have the following code: private static Dictionary<string , double > GetY(List<PointK> points) { var invertedDictResult = new Dictionary<string, double>(); foreach (var point in points) { if (!invertedDictResult.ContainsKey(point.Mark)) { invertedDictResult.Add(point .Mark, Math.Round(point.Y, 4)); } } return invertedDictResult; } private static Dictionary<string , double > GetX(List<PointK> points) { var invertedDictResult = new Dictionary<string, double>(); foreach (var point in points) { if (!invertedDictResult.ContainsKey(point.Mark)) { invertedDictResult.Add(point .Mark, Math.Round(point.X, 4)); } } return invertedDictResult; } How to restructure the above code?

    Read the article

  • JavaScript regex refactoring

    - by JamesBrownIsDead
    I'm performing this on a string: var poo = poo .replace(/[%][<]/g, "'<") .replace(/[>][%]/g, ">'") .replace(/[%]\s*[+]/g, "'+") .replace(/[+]\s*[%]/g, "+'"); Given the similar if these statements, can these regexs be comebined somehow?

    Read the article

  • Refactoring a javascript array rotate function

    - by ideotop
    I wrote a rotate function, but I'm not satisfied with it: var pixels=['011','110','000']; var result=new Array(); result=['000','000','000']; for ( y=0; y<(pixels.length); y++ ){ for ( x=0; x<(pixels.length); x++ ){ var newx=0,newy=0; if ( clock ){ if ( x< r.x && y< r.y ) {newx=x+2;newy=y ;}//top left if ( x==r.x && y< r.y ) {newx=x+1;newy=y+1;}//top if ( x> r.x && y< r.y ) {newx=x ;newy=y+2;}//top right if ( x< r.x && y==r.y ) {newx=x+1;newy=y-1;}//left if ( x==r.x && y==r.y ) {newx=x ;newy=y ;}//center if ( x> r.x && y==r.y ) {newx=x-1;newy=y+1;}//right if ( x< r.x && y> r.y ) {newx=x ;newy=y-2;}//bottom left if ( x==r.x && y> r.y ) {newx=x-1;newy=y-1;}//bottom if ( x> r.x && y> r.y ) {newx=x-2;newy=y ;}//bottom right } else { if ( x< r.x && y< r.y ) {newx=x ;newy=y+2;}//top left if ( x==r.x && y< r.y ) {newx=x-1;newy=y+1;}//top if ( x> r.x && y< r.y ) {newx=x-2;newy=y ;}//top right if ( x< r.x && y==r.y ) {newx=x+1;newy=y+1;}//left if ( x==r.x && y==r.y ) {newx=x ;newy=y ;}//center if ( x> r.x && y==r.y ) {newx=x-1;newy=y-1;}//right if ( x< r.x && y> r.y ) {newx=x+2;newy=y ;}//bottom left if ( x==r.x && y> r.y ) {newx=x+1;newy=y-1;}//bottom if ( x> r.x && y> r.y ) {newx=x ;newy=y-2;}//bottom right } //inject(result,newx,newy,pixels[y][x]) } } does someone now how to write a cleaner code for this rotate (clock and counter-clock) function ?

    Read the article

  • Java: JPA classes, refactoring from Date to DateTime

    - by bguiz
    With a table created using this SQL Create Table X ( ID varchar(4) Not Null, XDATE date ); and an entity class defined like so @Entity @Table(name = "X") public class X implements Serializable { @Id @Basic(optional = false) @Column(name = "ID", nullable = false, length = 4) private String id; @Column(name = "XDATE") @Temporal(TemporalType.DATE) private Date xDate; //java.util.Date ... } With the above, I can use JPA to achieve object relational mapping. However, the xDate attribute can only store dates, e.g. dd/MM/yyyy. How do I refactor the above to store a full date object using just one field, i.e. dd/MM/yyyy HH24:mm?

    Read the article

  • Help me refactoring this nasty Ruby if/else statement

    - by Suborx
    Hello, so I have this big method in my application for newsletter distribution. Method is for updating rayons and i need to assigned user to rayon. I have relation n:n through table colporteur_in_rayons witch have attributes since_date and _until_date. I am junior programmer and i know this code is pretty dummy :) I appreciated every suggestion. def update rayon = Rayon.find(params[:id]) if rayon.update_attributes(params[:rayon]) if params[:user_id] != "" unless rayon.users.empty? unless rayon.users.last.id.eql?(params[:user_id]) rayon.colporteur_in_rayons.last.update_attributes(:until_date = Time.now) Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been succesuly assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end else Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been successfully assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end end flash[:success] = "Rayon has been successfully updated." return redirect_to rayons_path else flash[:error] = "Rayon has not been updated." return redirect_to :back end end

    Read the article

  • Refactoring a leaf class to a base class, and keeping it also a interface implementation

    - by elcuco
    I am trying to refactor a working code. The code basically derives an interface class into a working implementation, and I want to use this implementation outside the original project as a standalone class. However, I do not want to create a fork, and I want the original project to be able to take out their implementation, and use mine. The problem is that the hierarchy structure is very different and I am not sure if this would work. I also cannot use the original base class in my project, since in reality it's quite entangled in the project (too many classes, includes) and I need to take care of only a subdomain of the problems the original project is. I wrote this code to test an idea how to implement this, and while it's working, I am not sure I like it: #include <iostream> // Original code is: // IBase -> Derived1 // I need to refactor Derive2 to be both indipendet class // and programmers should also be able to use the interface class // Derived2 -> MyClass + IBase // MyClass class IBase { public: virtual void printMsg() = 0; }; /////////////////////////////////////////////////// class Derived1 : public IBase { public: virtual void printMsg(){ std::cout << "Hello from Derived 1" << std::endl; } }; ////////////////////////////////////////////////// class MyClass { public: virtual void printMsg(){ std::cout << "Hello from MyClass" << std::endl; } }; class Derived2: public IBase, public MyClass{ virtual void printMsg(){ MyClass::printMsg(); } }; class Derived3: public MyClass, public IBase{ virtual void printMsg(){ MyClass::printMsg(); } }; int main() { IBase *o1 = new Derived1(); IBase *o2 = new Derived2(); IBase *o3 = new Derived3(); MyClass *o4 = new MyClass(); o1->printMsg(); o2->printMsg(); o3->printMsg(); o4->printMsg(); return 0; } The output is working as expected (tested using gcc and clang, 2 different C++ implementations so I think I am safe here): [elcuco@pinky ~/src/googlecode/qtedit4/tools/qtsourceview/qate/tests] ./test1 Hello from Derived 1 Hello from MyClass Hello from MyClass Hello from MyClass [elcuco@pinky ~/src/googlecode/qtedit4/tools/qtsourceview/qate/tests] ./test1.clang Hello from Derived 1 Hello from MyClass Hello from MyClass Hello from MyClass The question is My original code was: class Derived3: public MyClass, public IBase{ virtual void IBase::printMsg(){ MyClass::printMsg(); } }; Which is what I want to express, but this does not compile. I must admit I do not fully understand why this code work, as I expect that the new method Derived3::printMsg() will be an implementation of MyClass::printMsg() and not IBase::printMsg() (even tough this is what I do want). How does the compiler chooses which method to re-implement, when two "sister classes" have the same virtual function name? If anyone has a better way of implementing this, I would like to know as well :)

    Read the article

  • Refactoring or Rewriting Monolithic PHP Spaghetti Codebase

    - by nategood
    I've inherited a really poorly designed PHP spaghetti code project. It's been gaining a good bit of traffic recently and is starting to have performance issues on top of the poor monolithic code base. Its maxing out performance on a chunky 16GB dedicated machine when it really shouldn't be. I'm planning on doing some performance tweaks right off the bat to help the performance issue, but this still won't really help the horrible code base. The team is small but expecting to grow very soon. I've read Joel's article on the troubles of doing a complete rewrite and see the concerns. But how bad does the code base have to be before you consider a rewrite? There is PHP handling logic interjected into what one would usually consider a "view". Even worse, in some places SQL statements are in these same files! The only real separation of presentation and logic are a few PHP scripts that serve as function libraries. These scripts do most of the ORM stuff... if you can even call it that. Trying to slowly refractor this seems like a nightmare. Open to your thoughts and opinions... however not interested in hearing, "Run away, Run away!".

    Read the article

  • Refactoring routes - serving different layouts

    - by dmclark
    As a Rails NOOB, I started with a routes.rb of: ActionController::Routing::Routes.draw do |map| map.resources :events map.connect 'affiliates/list', :controller => "affiliates", :action => "list" map.connect 'affiliates/regenerate_thumb/:id', :controller => "affiliates", :action => "regenerate_thumb" map.connect 'affiliates/state/:id.:format', :controller => "affiliates", :action => "find_by_state" map.connect 'affiliates/getfeed', :controller => "affiliates", :action => "feed" map.resources :affiliates, :has_many => :events map.connect ":controller/:action" map.connect '', :controller => "affiliates" map.connect ":controller/:action/:id" map.connect ":controller/:action/:id/:format" end and i'm trying to tighten it up. and I've gotten as far as: ActionController::Routing::Routes.draw do |map| map.resources :events, :only => "index" map.resources :affiliates do |affiliates| affiliates.resources :has_many => :events affiliates.resources :collection => { :list => :get, :regenerate_thumb => "regenerate_thumb" } end # map.connect 'affiliates/regenerate_thumb/:id', :controller => "affiliates", :action => "regenerate_thumb" map.connect 'affiliates/state/:id.:format', :controller => "affiliates", :action => "find_by_state" map.connect 'affiliates/getfeed', :controller => "affiliates", :action => "feed" map.root :affiliates end what is confusing to me is routes vs parameters.. For example, I realized that the only difference between list and index is HOW it is rendered, rather than WHAT is rendered. Having a different action (as I do now) feels wrong but I can't figure out he right way. Thanks

    Read the article

  • Data layer refactoring

    - by Joey
    I've taken control of some entity framework code and am looking to refactor it. Before I do, I'd like to check my thoughts are correct and I'm not missing the entity-framework way of doing things. Example 1 - Subquery vs Join Here we have a one-to-many between As and Bs. Apart from the code below being hard to read, is it also inefficient? from a in dataContext.As where ((from b in dataContext.Bs where b.Text.StartsWith(searchText) select b.AId).Distinct()).Contains(a.Id) select a Would it be better, for example, to use the join and do something like this? from a in dataContext.As where a.Bs.Any(b => b.Text.StartsWith(searchText)) select a Example 2 - Explicit Joins vs Navigation Here we have a one-to-many between As and Bs and a one-to-many between Bs and Cs. from a in dataContext.As join b in dataContext.Bs on b.AId equals a.Id join c in dataContext.Cs on c.BId equals b.Id where c.SomeValue equals searchValue select a Is there a good reason to use explicit joins rather than navigating through the data model? For example: from a in dataContext.As where a.Bs.Any(b => b.Cs.Any(c => c.SomeValue == searchValue) select a

    Read the article

  • Pattern or recommneded refactoring for method

    - by iKode
    I've written a method that looks like this: public TimeSlotList processTimeSlots (DateTime startDT, DateTime endDT, string bookingType, IList<Booking> normalBookings, GCalBookings GCalBookings, List<DateTime> otherApiBookings) { { ..... common process code ...... while (utcTimeSlotStart < endDT) { if (bookingType == "x") { //process normal bookings using IList<Booking> normalBookings } else if (bookingType == "y") { //process google call bookings using GCalBookings GCalBookings } else if (bookingType == "z" { //process other apibookings using List<DateTime> otherApiBookings } } } So I'm calling this from 3 different places, each time passing a different booking type, and each case passing the bookings I'm interested in processing, as well as 2 empty objects that aren't used for this booking type. I'm not able to get bookings all into the same datatype, which would make this easier and each booking type needs to be processed differently, so I'm not sure how I can improve this. Any ideas?

    Read the article

  • Refactoring multiple if statements for user authentication with subdomains

    - by go minimal
    I'm building a typical web app where once a user signs up they access the app through their own subdomain (company.myapp.com). The "checking what kind of user if any is logged in" piece is starting to get very hairy and it obviously needs to be well-written because its run so often so I was wondering how you guys would re-factor this stuff. Here are the different states: A user must be logged in, the user must not have a company name, and the sub-domain must be blank A user must be logged in, the user must have a company name, that company name must match the current sub-domain A user must be logged in, the user must have a company name, that company name must match the current sub-domain, and the user's is_admin boolean is true if !session[:user_id].nil? @user = User.find(session[:user_id]) if @user.company.nil? && request.subdomains.first.nil? return "state1" elsif [email protected]? if @user.company.downcase == request.subdomains.first.downcase && [email protected]_admin return "state2" elsif @user.company.downcase == request.subdomains.first.downcase && @user.is_admin return "state3" end end end

    Read the article

  • Refactoring method that was previously injected with implement

    - by ryber
    Greetings, I'm trying to override or extend the Element.show() and .hide() methods in mootools in order to add some WAI-Aria toggling. I was trying to use the Class.Refactor() method like this: Element = Class.refactor(Element, { show: function(displayString) { result = this.previous(displayString); // Do my thing return result; }, hide: function() { result = this.previous(); // Do my thing return result; } }); however, this is not working, previous is null and I think the reason is that Mootools injects those methods through Element.implement. So the methods are not native? I have figured out how to completely replace .show and .hide but I would like to retain all of their existing functionality and just add to it. Any ideas?

    Read the article

  • Refactoring Rails 3 Routes

    - by Martin
    Hello, I have this in my routes: get '/boutique/new' => 'stores#new', :as => :new_store, :constraints => { :id => /[a-z0-9_-]/ } post '/boutique' => 'stores#create', :as => :create_store, :constraints => { :id => /[a-z0-9_-]/ } get '/:shortname' => 'stores#show', :as => :store, :constraints => { :id => /[a-z0-9_-]/ } get '/:shortname/edit' => 'stores#edit', :as => :edit_store, :constraints => { :id => /[a-z0-9_-]/ } put '/:shortname' => 'stores#update', :as => :update_store, :constraints => { :id => /[a-z0-9_-]/ } delete '/:shortname' => 'stores#delete', :as => :destroy_store, :constraints => { :id => /[a-z0-9_-]/ } Is there a cleaner way to do the same? It doesn't look any elegant and even less if I add some more controls/actions to it. Thank you.

    Read the article

  • Refactoring thick client legacy application

    - by Paul
    I am working on a fat client legacy C++ application which has a lot of business logic mixed in with the presentation side of things. I want to clean things out and refactor the code out completely, so there is a clear seperation of concerns. I am looking at MVC or some other suitable design pattern in order to achieve this. I would like to get recommendations from people who have walked this road before - Do I use MVP or MVC (or another pattern)? What is/are the best practices for undertaking something like this (i.e. useful steps/checks) ?

    Read the article

  • Javascript code refactoring and assessment

    - by neitony
    I'm using javascript to toggle the display state of some objects based on the time of day. A sample of the code is given below. I was wondering if anyone could give a suggestion as to how I can refactor this code while at the same time improving the logic. switch(tcode) { case 'eur' : eur.setAttribute('style', 'display:block; opacity:0.5'); us.style.display = 'none'; asia.style.display = 'none'; us_inactive.style.display = 'block'; asia_inactive.style.display = 'block'; break; case 'us' : us.style.display = 'block'; eur.style.display = 'none'; asia.style.display = 'none'; eur_inactive.style.display = 'block'; asia_inactive.style.display = 'block'; break; case 'asia' : asia.setAttribute('style', 'display:block; opacity:0.5'); us.style.display = 'none'; eur.style.display = 'none'; eur_inactive.style.display = 'block'; us_inactive.style.display = 'block';

    Read the article

  • Refactoring and assessment

    - by neitony
    I'm using javascript to toggle the display state of some objects based on the time of day. A sample of the code is given below. I was wondering if anyone could give a suggestion as to how I can refactor this code while at the same time improving the logic. switch(tcode) { case 'eur' : eur.setAttribute('style', 'display:block; opacity:0.5'); us.style.display = 'none'; asia.style.display = 'none'; us_inactive.style.display = 'block'; asia_inactive.style.display = 'block'; break; case 'us' : us.style.display = 'block'; eur.style.display = 'none'; asia.style.display = 'none'; eur_inactive.style.display = 'block'; asia_inactive.style.display = 'block'; break; case 'asia' : asia.setAttribute('style', 'display:block; opacity:0.5'); us.style.display = 'none'; eur.style.display = 'none'; eur_inactive.style.display = 'block'; us_inactive.style.display = 'block';

    Read the article

  • Refactoring one large list of C# properties/fields

    - by dotnetdev
    If you take a look at http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/activedirectoryoperations11132009113015AM/activedirectoryoperations.aspx, there is a huge list of properties for AD in one class. What is a good way to refactor such a large list of (Related) fields? Would making seperate classes be adequate or is there a better way to make this more manageable? Thanks

    Read the article

  • refactoring this function in Java

    - by Joel
    Hi folks, I'm learning Java, and I know one of the big complaints about newbie programmers is that we make really long and involved methods that should be broken into several. Well here is one I wrote and is a perfect example. :-D. public void buildBall(){ /* sets the x and y value for the center of the canvas */ double i = ((getWidth() / 2)); double j = ((getHeight() / 2)); /* randomizes the start speed of the ball */ vy = 3.0; vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(.05)) vx = -vx; /* creates the ball */ GOval ball = new GOval(i,j,(2 *BALL_RADIUS),(2 * BALL_RADIUS)); ball.setFilled(true); ball.setFillColor(Color.RED); add(ball); /* animates the ball */ while(true){ i = (i + (vx* 2)); j = (j + (vy* 2)); if (i > APPLICATION_WIDTH-(2 * BALL_RADIUS)){ vx = -vx; } if (j > APPLICATION_HEIGHT-(2 * BALL_RADIUS)){ vy = -vy; } if (i < 0){ vx = -vx; } if (j < 0){ vy = -vy; } ball.move(vx + vx, vy + vy); pause(10); /* checks the edges of the ball to see if it hits an object */ colider = getElementAt(i, j); if (colider == null){ colider = getElementAt(i + (2*BALL_RADIUS), j); } if (colider == null){ colider = getElementAt(i + (2*BALL_RADIUS), j + (2*BALL_RADIUS)); } if (colider == null){ colider = getElementAt(i, j + (2*BALL_RADIUS)); } /* If the ball hits an object it reverses direction */ if (colider != null){ vy = -vy; /* removes bricks when hit but not the paddle */ if (j < (getHeight() -(PADDLE_Y_OFFSET + PADDLE_HEIGHT))){ remove(colider); } } } You can see from the title of the method that I started with good intentions of "building the ball". There are a few issues I ran up against: The problem is that then I needed to move the ball, so I created that while loop. I don't see any other way to do that other than just keep it "true", so that means any other code I create below this loop won't happen. I didn't make the while loop a different function because I was using those variables i and j. So I don't see how I can refactor beyond this loop. So my main question is: How would I pass the values of i and j to a new method: "animateBall" and how would I use ball.move(vx + vx, vy + vy); in that new method if ball has been declared in the buildBall method? I understand this is probably a simple thing of better understanding variable scope and passing arguments, but I'm not quite there yet...

    Read the article

  • refactoring my code. My headers (Header Guard Issues)

    - by numerical25
    I had a post similar to this awhile ago based on a error I was getting. I was able to fix it but since then I been having trouble doing things because headers keep blocking other headers from using code. Honestly, these headers are confusing me and if anyone has any resources that will address these types of issues, that will be helpful. What I essentially want to do is be able to have rModel.h be included inside RenderEngine.h. every time I add rModel.h to RenderEngine.h, rModel.h is no longer able to use RenderEngine.h. (rModel.h has a #include of RenderEngine.h as well). So in a nutshell, RenderEngine and rModel need to use each others functionalities. On top of all this confusion, the Main.cpp needs to use RenderEngine. stdafx.h #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> // C RunTime Header Files #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include "resource.h" main.cpp #include "stdafx.h" #include "RenderEngine.h" #include "rModel.h" // Global Variables: RenderEngine go; rModel *g_pModel; ...code........... rModel.h #ifndef _MODEL_H #define _MODEL_H #include "stdafx.h" #include <vector> #include <string> #include "rTri.h" #include "RenderEngine.h" ........Code RenderEngine.h #pragma once #include "stdafx.h" #include "d3d10.h" #include "d3dx10.h" #include "dinput.h" #include "rModel.h" .......Code......

    Read the article

  • Refactoring nested foreach statement

    - by dotnetdev
    Hi, I have a method with a nested foreach collection (iterate a set of objects and then look inside each object). I saw in a book a good pattern to make this much more elegant but cannot remember/find the code example. How else could I make this more tidy? The code is just a typical nested foreach statement so I have not provided a code sample. Thanks

    Read the article

  • Testing local scoped object with mockito without refactoring

    - by supertonsky
    Say I have the following code: public class ClassToTest { AnotherClass anotherClass; public void methodToTest( int x, int y ) { int z = x + y anotherClass.receiveSomething( z ); } } public class AnotherClass { public void receiveSomething( int z ) {.. do something.. } } I want to make assertion on the value of the variable z. How do I do this? Variables x, y, and z could be some other Java class types, and I just used "int" for simplicity.

    Read the article

  • Refactoring FAT client legacy application

    - by Paul
    I am working on a fat client legacy C++ application which has a lot of business logic mixed in with the presentation side of things. I want to clean things out and refactor the code out completely, so there is a clear seperation of concerns. I am looking at MVC or some other suitable design pattern in order to achieve this. I would like to get recommendations from people who have walked this road before - Do I use MVP or MVC (or another pattern)? What is/are the best practices for undertaking something like this (i.e. useful steps/checks) ?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >