• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 09:29
CEST 15:29
KST 22:29
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4Team Liquid Map Contest #21 - Presented by Monster Energy9uThermal's 2v2 Tour: $15,000 Main Event18Serral wins EWC 202549
Community News
Maestros of The Game—$20k event w/ live finals in Paris23Weekly Cups (Aug 11-17): MaxPax triples again!13Weekly Cups (Aug 4-10): MaxPax wins a triple6SC2's Safe House 2 - October 18 & 195Weekly Cups (Jul 28-Aug 3): herO doubles up6
StarCraft 2
General
What mix of new and old maps do you want in the next 1v1 ladder pool? (SC2) : 2v2 & SC: Evo Complete: Weekend Double Feature Geoff 'iNcontroL' Robinson has passed away The GOAT ranking of GOAT rankings RSL Revival patreon money discussion thread
Tourneys
RSL: Revival, a new crowdfunded tournament series Maestros of The Game—$20k event w/ live finals in Paris Sparkling Tuna Cup - Weekly Open Tournament Monday Nights Weeklies Master Swan Open (Global Bronze-Master 2)
Strategy
Custom Maps
External Content
Mutation # 487 Think Fast Mutation # 486 Watch the Skies Mutation # 485 Death from Below Mutation # 484 Magnetic Pull
Brood War
General
Flash On His 2010 "God" Form, Mind Games, vs JD BGH Auto Balance -> http://bghmmr.eu/ Joined effort New season has just come in ladder BW General Discussion
Tourneys
[ASL20] Ro24 Group B [ASL20] Ro24 Group C BWCL Season 63 Announcement [CSLPRO] It's CSLAN Season! - Last Chance
Strategy
Simple Questions, Simple Answers Fighting Spirit mining rates [G] Mineral Boosting Muta micro map competition
Other Games
General Games
Nintendo Switch Thread General RTS Discussion Thread Dawn of War IV Path of Exile Stormgate/Frost Giant Megathread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread The year 2050 Things Aren’t Peaceful in Palestine European Politico-economics QA Mega-thread
Fan Clubs
INnoVation Fan Club SKT1 Classic Fan Club!
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece [\m/] Heavy Metal Thread
Sports
2024 - 2026 Football Thread TeamLiquid Health and Fitness Initiative For 2023 Formula 1 Discussion
World Cup 2022
Tech Support
High temperatures on bridge(s) Gtx660 graphics card replacement Installation of Windows 10 suck at "just a moment"
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
Evil Gacha Games and the…
ffswowsucks
Breaking the Meta: Non-Stand…
TrAiDoS
INDEPENDIENTE LA CTM
XenOsky
[Girl blog} My fema…
artosisisthebest
Sharpening the Filtration…
frozenclaw
ASL S20 English Commentary…
namkraft
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2202 users

The Big Programming Thread - Page 357

Forum Index > General Forum
Post a Reply
Prev 1 355 356 357 358 359 1031 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
sluggaslamoo
Profile Blog Joined November 2009
Australia4494 Posts
Last Edited: 2013-09-19 03:32:11
September 19 2013 03:30 GMT
#7121
On September 19 2013 11:35 berated- wrote:
Show nested quote +
On September 19 2013 11:05 sluggaslamoo wrote:
On September 19 2013 10:47 berated- wrote:
On September 19 2013 10:16 sluggaslamoo wrote:
On September 19 2013 01:58 Morfildur wrote:
On September 18 2013 12:57 sluggaslamoo wrote:
On September 18 2013 08:45 berated- wrote:
On September 18 2013 08:33 sluggaslamoo wrote:
On September 17 2013 16:20 WindWolf wrote:
On September 17 2013 15:06 sluggaslamoo wrote:
[quote]

There are plenty of reasons. In this case it could make the code hard to debug. Someone could easily already be using setSeed() deeply nested within some code file.

Then when your code doesn't randomize differently, you are sitting their scratching your head why your RNG code didn't work when really it was setSeed causing the issue.

The seed should be set in the initialiser or as a config variable or both. You aren't going to need to set the seed on the fly for RNG in a game. When the game starts you initialise the RNG object with the seed using the game's config table, after that it doesn't need to change until the next game. This allows you to isolate the issue and make debugging much easier.

IMO it is also simpler and much more intuitive than using setSeed.

I didn't meant about RNG's specifically, I was just the principal of using a set method for a long piece of code instead of writing all of that code again.

And even is setSeed isn't a good name, what would make for a good name (we can take the debate on whenever you should be able to change the seed of a RGN or not another time)


The same principle still applies for lots of things. You want to reduce the amount of side effects to a minimum in order to make maintenance easier. I can't even remember the last time I have used a setter.


Can you make some clarifications, for those of us in the peanut gallery.

What language do you do most of your programming in? And what are the size of the projects you work on? Also, are you excluding domain objects from outside of your discussions of getters and setters are bad.


I use Ruby mostly, but in certain companies I have had to deal with other languages, and I've worked on both small and behemoth monolithic Java projects.

Basically what phar said. For every time you allow something to change, it means one extra thing you have to think of when debugging.

Setting is best left to initialisers or factories, then the object performs services using those parameters and keeps everything self contained. Instead of using setters, you can create a new object with new parameters.

Think of it as people working within an organisation, you don't set attributes to people, you have different people who are capable of doing different things. "Hire" the people you need, then hand off the work to each of these people to get the work done.

In Ruby I also tend to do a lot of things functionally, which removes the issue of side effects, but you also don't have these hand offs between objects when really you just want something short and sweet.

Its very hard to do right and will take years to figure out how to be able to do it in a way that makes the code look better not worse, let alone figure it out quickly. Just realise that in the long term you are going to be much better off.

The reason people write setters is because they don't realise other patterns exist to allow you to perform operations without them.


While that sounds nice in theory, not using setters at all often produces needless overhead.

Take for an example a simple forum with user management. You have users, users have passwords and passwords are encrypted and occasionally get changed. In your example, everytime a user changes his password, you would clone the old user object with a different password parameter, which is a lot more overhead than taking an existing object and simply changing a property of it through a setter.

A simple "SetPassword(new Password)" method is easier to read, write and understand with exactly zero useless overhead. You can even hide the password encrypting, salting, spicing and garnishing behind it and not use a getter because passwords are 1-way encrypted and reading it doesn't make sense.

Yes, there are lots of getters/setters that are bad and i'm usually in favour of only using what is really neccessary and not go by the internal datastructure of the object, but there are also lots of legitimate reasons to use getters/setters, even in semi-functional languages like ruby. You just always have to think before blindly creating getters and setters, which admittedly is something not a lot of programmers do. Setters should never be a replacement for a proper constructor nor be required to initialize an object; That should always happen in the constructor so the object always has a valid state.


Not trying to sound arrogant or anything, but I think its funny to say "it sounds nice in theory" when it is actually something I do in my profession all the time.

For databasing you should have a library which prevents you from having to use or write setters. Good libraries will provide an abstraction which takes you away from the process of having to manage data manually, mitigating the risk of human error. You then declare you database strategy, your validations, and data processing methods, and your library should handle the rest.

Sure in the end, you are still "setting" data but because it is all automated and declarative you are reducing side-effects to a minimum.

For example you will first be encapsulating the process in a transaction which gives you fail fast and rollback capabilities. Second of all instead of using setPassword, you would be using a system which takes form data and processes it automatically.

Any fields that are changed are processed within a transaction, if there are any errors it is rolled back, if not the transaction is committed and any processing required, e.g creating an encrypted password, is executed without procedural programming involved.

Feel free to keep shooting me examples. Keep in mind we are talking in the context of using OOP, which mostly useful for websites and business applications. The only thing I can think of where setters will be used extensively will be in an application where full OOP is not ideal, like traditional games.

EDIT:
I think I should clarify and answer your question more specifically.

Sometimes its impossible to avoid side-effects or setting data, your example is a good one. When you have to save user data, its physically impossible not to "set" data, it wouldn't make sense not to.

But as I said earlier, the only reason it doesn't make sense not to use a "setter" in this example is because you haven't learned a pattern to avoid doing so. There is always more overhead in writing and using setters.

To provide a solution to your example specifically.
- I would use a database library which handles my form data.
- I write a callback in my database which automatically encrypts and save the password whenever it changes.
- When the user submits form data which includes a password, the database library executes the callback which encrypts the password

This is much more elegant to using setPassword(), which I'm sure you would understand the headaches involved when it would come to maintaining very large program. You would have to make sure setPassword() is called in all the appropriate user save methods, finding those methods would take you hours in a corporate business application, and you would have to make sure that every other programmer knows to use it as well.

Having an on_change callback solves all these problems, if a person puts a password field in a new page that I don't know of, it will still take effect. Now I am completely abstracted away from the database management process. I don't need to use set() or save() anywhere in my code which makes my life much easier when I run into any problems.


This assumes that you are able to use a library like the ones used in ruby, python, or hibernate for java. Sometimes the sql that you have is so complex because you don't control the schema that this isn't possible. The strategy used for these is great for simple schemas, not so much when the schemas get super complex. This isn't an excuse to allow for poorly designed code, just sayin...

The thing to note here is that every in development is about trade offs. Even Holub's article on javaworld touches on this. Encapsulating all the code in the model is great because it allows for you to only touch the parts of code that you want to touch. Using libraries that handle this is even better.

What if you decided though that relational databases are complete shit, and nosql is the way to go? You would either have to redo all the libraries that were done for sql, or you hope that in that instance you wrote your own DAO layer and now you can just swap that out instead of having to touch all the rest of your model code.

Design is hard.


When the schemas get super complex that's when this system becomes even better, however there should really never really be a time when your schemas get super complex. If that happens you are really over-engineering. I've worked with some very complex schemas using this system, I myself like to keep things very simple but that's probably due to the fact that things can be much simpler with ODM than SQL.

In my case most libraries reserve the same words as active_record, so swapping between a relational database and a document oriented database is a piece of cake. However in a large application the company wouldn't bother to give you the time to do this anyway.

All I'm doing is giving an appropriate example which in this case I'm assuming Java. Sure there are some edge cases where some obscure programming language won't have an appropriate library to do that, but there's nothing to be gained from using those examples in this debate.

It just seems silly to bring up an edge case example where you have to be dead set on writing setters. You may as well bring up C and ask how to write a website in it without using setters, then when I can't answer you just say "hah! see I told you!".

If an obscure language which nobody uses doesn't provide a library, I think many people would appreciate you writing the library yourself and sharing it . Otherwise don't use that language, any problems you face you brought upon yourself.


I guess your edge is my daily reality, and my edge is your daily reality. It seems silly to me to talk about running a website and calling that the normal case. It's kind of hard to keep running a warehouse a simple process.

I'm by no means saying you're wrong, just simply observing that making an absolute statement like getters and setters are bad, and that languages that use them are _terrible_ languages is pretty bold. The only point I'm trying to raise is that everything is about tradeoffs, and while one might prefer to avoid getters and setters, that doing so should be weighed and debated on a situational basis instead of an absolution.

Edit: I'm far down on the list though, so, I should probably bow out of this conversation. :D


Well when you are talking about from the perspective of a database warehouse we are moving away from the debate about design because sacrifices are often made for legacy systems and performance.

Its not that you can't have simple schemas and have to use getters and setters, its that you are working with old technology and veteran programmers so there isn't a valid business case for moving towards re-factoring and more advanced technology.

From a design sense its bad, and if you were creating a database warehouse in 2013 the arguments I made would still apply. At some point we won't be using these systems any more. At one point using getters and setters was probably the thing to do, but we have to realise that just because you are stuck with veteran programmers living in 1990 are still doing it, doesn't make it good practice to do it yourself.

I'm sure if you had a warehouse running in NodeJS using CouchDB you wouldn't have a "complex" schema no matter how granular and powerful your system is because you don't have to deal with complex join tables or migrations. And you would have scalable performance through replication/concurrency rather than optimisation through code.

From a design perspective, talking about using legacy systems or having to deal with a team of programmers that design systems like we are still in the 90's isn't really in the scope of the argument. It doesn't really prevent you from doing what I said, its just that you are forced into using bad programming practices due to outside influences.
Come play Android Netrunner - http://www.teamliquid.net/forum/viewmessage.php?topic_id=409008
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
September 19 2013 07:10 GMT
#7122
On September 19 2013 08:28 Azerbaijan wrote:
So from all this discussion about getters and setters I have gathered that I should generally avoid them except in very specific situations where their use will not cause problems later?

You should use them freely, as long as you need them. When you're writing a class, you should first design it. What does the class do, what should it be used for. When you have this interface, you'll know if you need any accessors (setters/getters). Later when you implement the class, only implement those very accessors. How you handle the rest of your internal variables is up to you, some people prefer private accessors, others just use the variables directly since it's slightly faster, reduces amount of code and if you break something, it's internal to the class anyway.

The main point is not really if you should use accessors (you should) but how much you should make public, and the answer is of course, as little as possible.
berated-
Profile Blog Joined February 2007
United States1134 Posts
Last Edited: 2013-09-19 11:24:57
September 19 2013 10:12 GMT
#7123
On September 19 2013 12:30 sluggaslamoo wrote:
Show nested quote +
On September 19 2013 11:35 berated- wrote:
On September 19 2013 11:05 sluggaslamoo wrote:
On September 19 2013 10:47 berated- wrote:
On September 19 2013 10:16 sluggaslamoo wrote:
On September 19 2013 01:58 Morfildur wrote:
On September 18 2013 12:57 sluggaslamoo wrote:
On September 18 2013 08:45 berated- wrote:
On September 18 2013 08:33 sluggaslamoo wrote:
On September 17 2013 16:20 WindWolf wrote:
[quote]
I didn't meant about RNG's specifically, I was just the principal of using a set method for a long piece of code instead of writing all of that code again.

And even is setSeed isn't a good name, what would make for a good name (we can take the debate on whenever you should be able to change the seed of a RGN or not another time)


The same principle still applies for lots of things. You want to reduce the amount of side effects to a minimum in order to make maintenance easier. I can't even remember the last time I have used a setter.


Can you make some clarifications, for those of us in the peanut gallery.

What language do you do most of your programming in? And what are the size of the projects you work on? Also, are you excluding domain objects from outside of your discussions of getters and setters are bad.


I use Ruby mostly, but in certain companies I have had to deal with other languages, and I've worked on both small and behemoth monolithic Java projects.

Basically what phar said. For every time you allow something to change, it means one extra thing you have to think of when debugging.

Setting is best left to initialisers or factories, then the object performs services using those parameters and keeps everything self contained. Instead of using setters, you can create a new object with new parameters.

Think of it as people working within an organisation, you don't set attributes to people, you have different people who are capable of doing different things. "Hire" the people you need, then hand off the work to each of these people to get the work done.

In Ruby I also tend to do a lot of things functionally, which removes the issue of side effects, but you also don't have these hand offs between objects when really you just want something short and sweet.

Its very hard to do right and will take years to figure out how to be able to do it in a way that makes the code look better not worse, let alone figure it out quickly. Just realise that in the long term you are going to be much better off.

The reason people write setters is because they don't realise other patterns exist to allow you to perform operations without them.


While that sounds nice in theory, not using setters at all often produces needless overhead.

Take for an example a simple forum with user management. You have users, users have passwords and passwords are encrypted and occasionally get changed. In your example, everytime a user changes his password, you would clone the old user object with a different password parameter, which is a lot more overhead than taking an existing object and simply changing a property of it through a setter.

A simple "SetPassword(new Password)" method is easier to read, write and understand with exactly zero useless overhead. You can even hide the password encrypting, salting, spicing and garnishing behind it and not use a getter because passwords are 1-way encrypted and reading it doesn't make sense.

Yes, there are lots of getters/setters that are bad and i'm usually in favour of only using what is really neccessary and not go by the internal datastructure of the object, but there are also lots of legitimate reasons to use getters/setters, even in semi-functional languages like ruby. You just always have to think before blindly creating getters and setters, which admittedly is something not a lot of programmers do. Setters should never be a replacement for a proper constructor nor be required to initialize an object; That should always happen in the constructor so the object always has a valid state.


Not trying to sound arrogant or anything, but I think its funny to say "it sounds nice in theory" when it is actually something I do in my profession all the time.

For databasing you should have a library which prevents you from having to use or write setters. Good libraries will provide an abstraction which takes you away from the process of having to manage data manually, mitigating the risk of human error. You then declare you database strategy, your validations, and data processing methods, and your library should handle the rest.

Sure in the end, you are still "setting" data but because it is all automated and declarative you are reducing side-effects to a minimum.

For example you will first be encapsulating the process in a transaction which gives you fail fast and rollback capabilities. Second of all instead of using setPassword, you would be using a system which takes form data and processes it automatically.

Any fields that are changed are processed within a transaction, if there are any errors it is rolled back, if not the transaction is committed and any processing required, e.g creating an encrypted password, is executed without procedural programming involved.

Feel free to keep shooting me examples. Keep in mind we are talking in the context of using OOP, which mostly useful for websites and business applications. The only thing I can think of where setters will be used extensively will be in an application where full OOP is not ideal, like traditional games.

EDIT:
I think I should clarify and answer your question more specifically.

Sometimes its impossible to avoid side-effects or setting data, your example is a good one. When you have to save user data, its physically impossible not to "set" data, it wouldn't make sense not to.

But as I said earlier, the only reason it doesn't make sense not to use a "setter" in this example is because you haven't learned a pattern to avoid doing so. There is always more overhead in writing and using setters.

To provide a solution to your example specifically.
- I would use a database library which handles my form data.
- I write a callback in my database which automatically encrypts and save the password whenever it changes.
- When the user submits form data which includes a password, the database library executes the callback which encrypts the password

This is much more elegant to using setPassword(), which I'm sure you would understand the headaches involved when it would come to maintaining very large program. You would have to make sure setPassword() is called in all the appropriate user save methods, finding those methods would take you hours in a corporate business application, and you would have to make sure that every other programmer knows to use it as well.

Having an on_change callback solves all these problems, if a person puts a password field in a new page that I don't know of, it will still take effect. Now I am completely abstracted away from the database management process. I don't need to use set() or save() anywhere in my code which makes my life much easier when I run into any problems.


This assumes that you are able to use a library like the ones used in ruby, python, or hibernate for java. Sometimes the sql that you have is so complex because you don't control the schema that this isn't possible. The strategy used for these is great for simple schemas, not so much when the schemas get super complex. This isn't an excuse to allow for poorly designed code, just sayin...

The thing to note here is that every in development is about trade offs. Even Holub's article on javaworld touches on this. Encapsulating all the code in the model is great because it allows for you to only touch the parts of code that you want to touch. Using libraries that handle this is even better.

What if you decided though that relational databases are complete shit, and nosql is the way to go? You would either have to redo all the libraries that were done for sql, or you hope that in that instance you wrote your own DAO layer and now you can just swap that out instead of having to touch all the rest of your model code.

Design is hard.


When the schemas get super complex that's when this system becomes even better, however there should really never really be a time when your schemas get super complex. If that happens you are really over-engineering. I've worked with some very complex schemas using this system, I myself like to keep things very simple but that's probably due to the fact that things can be much simpler with ODM than SQL.

In my case most libraries reserve the same words as active_record, so swapping between a relational database and a document oriented database is a piece of cake. However in a large application the company wouldn't bother to give you the time to do this anyway.

All I'm doing is giving an appropriate example which in this case I'm assuming Java. Sure there are some edge cases where some obscure programming language won't have an appropriate library to do that, but there's nothing to be gained from using those examples in this debate.

It just seems silly to bring up an edge case example where you have to be dead set on writing setters. You may as well bring up C and ask how to write a website in it without using setters, then when I can't answer you just say "hah! see I told you!".

If an obscure language which nobody uses doesn't provide a library, I think many people would appreciate you writing the library yourself and sharing it . Otherwise don't use that language, any problems you face you brought upon yourself.


I guess your edge is my daily reality, and my edge is your daily reality. It seems silly to me to talk about running a website and calling that the normal case. It's kind of hard to keep running a warehouse a simple process.

I'm by no means saying you're wrong, just simply observing that making an absolute statement like getters and setters are bad, and that languages that use them are _terrible_ languages is pretty bold. The only point I'm trying to raise is that everything is about tradeoffs, and while one might prefer to avoid getters and setters, that doing so should be weighed and debated on a situational basis instead of an absolution.

Edit: I'm far down on the list though, so, I should probably bow out of this conversation. :D


Well when you are talking about from the perspective of a database warehouse we are moving away from the debate about design because sacrifices are often made for legacy systems and performance.

Its not that you can't have simple schemas and have to use getters and setters, its that you are working with old technology and veteran programmers so there isn't a valid business case for moving towards re-factoring and more advanced technology.

From a design sense its bad, and if you were creating a database warehouse in 2013 the arguments I made would still apply. At some point we won't be using these systems any more. At one point using getters and setters was probably the thing to do, but we have to realise that just because you are stuck with veteran programmers living in 1990 are still doing it, doesn't make it good practice to do it yourself.

I'm sure if you had a warehouse running in NodeJS using CouchDB you wouldn't have a "complex" schema no matter how granular and powerful your system is because you don't have to deal with complex join tables or migrations. And you would have scalable performance through replication/concurrency rather than optimisation through code.

From a design perspective, talking about using legacy systems or having to deal with a team of programmers that design systems like we are still in the 90's isn't really in the scope of the argument. It doesn't really prevent you from doing what I said, its just that you are forced into using bad programming practices due to outside influences.


I wasn't talking about a data warehouse, I was referring to a pick pack and ship warehouse.

Still not disagreeing with you though, I believe that it is best to strive what you are talking about, just stating that there are some problems that are larger than a website which is why languages like java and c# exist, they arent just around to be terrible. Not every project gets to be fully theoretical and designed to be perfect even with brand new development, there are real world tradeoffs to the design decisions you make.

Btw, I'd be interested to see a WMS written in NodeJS, although that much JS sounds a little painful.

Edit: You obviously know what you are talking about so when you make simple statements like get/set is bad it comes from a long train of experience and choices. My intent whether articulated or not is that it takes that type of experience to reach that type of conclusion, and people who are learning from guys like you might miss the subtleness in your words because they don't have the same knowledge.
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
Last Edited: 2013-09-19 13:33:54
September 19 2013 13:33 GMT
#7124
I was wondering today if one has an ArrayList of objects (e.g. Person) with different attributes.

E.g.

Person
- name: String
- nationality: String
- age: int

What if you decide to have them sorted by name, nationality or age at any time? Say I want a list of every person sorted by age. In a minute, I want to see a list of every person sorted by nationality, etc.

What should the solution would be? To have N ArrayLists? To connect your application to a DB server? To dynamically sort?

It's not homework or anything I have to do. I'm just thinking what the best decision would be.

My thoughts:

1. Having 3 or N ArrayLists may be very memory consuming but it depends on the number of objects.
2. Having DB & SQL would be nice if allowed in such a case.


P.S. I usually use Java.
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
Last Edited: 2013-09-19 13:40:45
September 19 2013 13:37 GMT
#7125
On September 19 2013 22:33 darkness wrote:
I was wondering today if one has an ArrayList of objects (e.g. Person) with different attributes.

E.g.

Person
- name: String
- nationality: String
- age: int

What if you decide to have them sorted by name, nationality or age at any time? Say I want a list of every person sorted by age. In a minute, I want to see a list of every person sorted by nationality, etc.

What should the solution would be? To have N ArrayLists? To connect your application to a DB server? To dynamically sort?

It's not homework or anything I have to do. I'm just thinking what the best decision would be.

My thoughts:

1. Having 3 or N ArrayLists may be very memory consuming but it depends on the number of objects.
2. Having DB & SQL would be nice if allowed in such a case.


P.S. I usually use Java.

I don't know about Java, but in C# one would probably use LINQ to sort dynamically, it basically lets you run SQL like queries towards collections. For example, if you had an array of Employee objects called employees, you would write the following to get the list sorted by nationality:


var sorted = from e in employees
orderby e.Nationality
select e


sorted would then be a collection of all employees ordered by nationality.

It seems like a situation where one would like a database, assuming there's enough objects and persistance is important. It depends on what kind of project it is I guess.
fabiano
Profile Blog Joined August 2009
Brazil4644 Posts
September 19 2013 13:48 GMT
#7126
In java you can use Collections.

Very easy, check it on Stack Overflow.
"When the geyser died, a probe came out" - SirJolt
Yoshi-
Profile Joined October 2008
Germany10227 Posts
September 19 2013 13:51 GMT
#7127
On September 19 2013 22:33 darkness wrote:
I was wondering today if one has an ArrayList of objects (e.g. Person) with different attributes.

E.g.

Person
- name: String
- nationality: String
- age: int

What if you decide to have them sorted by name, nationality or age at any time? Say I want a list of every person sorted by age. In a minute, I want to see a list of every person sorted by nationality, etc.

What should the solution would be? To have N ArrayLists? To connect your application to a DB server? To dynamically sort?

It's not homework or anything I have to do. I'm just thinking what the best decision would be.

My thoughts:

1. Having 3 or N ArrayLists may be very memory consuming but it depends on the number of objects.
2. Having DB & SQL would be nice if allowed in such a case.


P.S. I usually use Java.


Well, depends if the data comes out of a DB there is not reason not to use it to sort.
If no DB is used and there is no reason for a DB(for whatever reasons), you should just dynamically sort it, I am sure that Java already has some sorting functions, if not something like Quicksort should be rather easy to implement.
Zocat
Profile Joined April 2010
Germany2229 Posts
September 19 2013 13:58 GMT
#7128
As always there's no "correct" solution with what you have given.

Having 3 different lists makes adding new Persons expensive (since you have to manipulate 3 lists, keep them synchronized with maybe threading issues, ...). On the other hand if you only have 1 list and dynamically sort , it might be inefficient, if you change the sorting very often. Just running a DB behind it might be over the top for maybe just a simple application.

If you have no idea: dynamically sort. Most straightforward one. You probably need to read up on Comparable though.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2013-09-19 15:08:53
September 19 2013 15:03 GMT
#7129
You most likely are just fine with dynamical sort. That should be your goto implementation at first, it's simple and intuitive. Don't even think about efficiency at first.

Then if it turns out your list is too large to be sorted on the fly (after actual profiling!), consider that you only need N lists of Person references, not actual Person objects. Since your original list also is a list of references, and a Person object probably is significantly larger than a Person reference, the additional memory consumption might not be so much. Obviously you would want to wrap such a multiple lists approach into a nice class that hides all the ugly insertion/deletion stuff. Oh and you probably want to use something more suitable for sorted sets/multisets than an ArrayList, whatever sorted container your language has.
If you have a good reason to disagree with the above, please tell me. Thank you.
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
Last Edited: 2013-09-19 17:13:04
September 19 2013 15:13 GMT
#7130
On September 19 2013 22:48 fabiano wrote:
In java you can use Collections.

Very easy, check it on Stack Overflow.


Thanks.

Personally, I like this answer from your link:

http://stackoverflow.com/a/1206246/1091781

It looks very tidy and straightforward imho.

Edit: It actually reminds me of C's built-in qsort.
Requizen
Profile Blog Joined March 2011
United States33802 Posts
September 19 2013 16:22 GMT
#7131
This is likely a simple solution that I'm too dumb to see.

C#: I have 3 user controls that are the 3 steps in a form (appropriately names Step1, Step2, Step3). As of right now, they're all just on separate pages and finishing one calls a Redirect() to the next page.

What is the best way to have them "call" each other on the same page, as in replacing the current one with the next one while remaining on the same ASP page?
It's your boy Guzma!
supereddie
Profile Joined March 2011
Netherlands151 Posts
September 19 2013 16:26 GMT
#7132
Use the Wizard: http://msdn.microsoft.com/en-us/library/fs0za4w6.aspx
"Do not try to make difficult things possible, but make simple things simple." - David Platt on Software Design
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
September 20 2013 06:53 GMT
#7133
On September 20 2013 01:22 Requizen wrote:
This is likely a simple solution that I'm too dumb to see.

C#: I have 3 user controls that are the 3 steps in a form (appropriately names Step1, Step2, Step3). As of right now, they're all just on separate pages and finishing one calls a Redirect() to the next page.

What is the best way to have them "call" each other on the same page, as in replacing the current one with the next one while remaining on the same ASP page?

Using the wizard component is definitely best practice.

If you want to roll your own, you could just put them in three different Panels on the same page, then flip the visible switch.
obesechicken13
Profile Blog Joined July 2008
United States10467 Posts
September 20 2013 21:24 GMT
#7134
I just got out from using a really old ubuntu os on a clunky machine.

Holy crap. I can't even write to my usb drive. Linux has come a long way from that user unfriendliness. Google didn't help much either so I doubt the error codes were too useful.

I ended up trying to remove permissions on the windows side and still nothing worked. Someone else reformatted a usb drive on windows and it was still read only...

I'm thinking I should go home and see which usb sticks I have there and try them all out on Monday. Otherwise maybe the lab machines have cd drives because they sure as hell aren't connected to the internet. I guess if I wanted to I could connect one to an open ethernet port using a long wire then transfer over the web using say dropbox.
I think in our modern age technology has evolved to become more addictive. The things that don't give us pleasure aren't used as much. Work was never meant to be fun, but doing it makes us happier in the long run.
bypLy
Profile Joined June 2013
757 Posts
September 22 2013 00:32 GMT
#7135
i am trying to build a 3d engine from scratch in an semi professional language (GL Basic). first i tried with vector matrix and z buffering but then i switched to ray casting style (doom)
the problem i always encounter is that at a certain point the performance goes rapidly down during rendering. a loop like:
+ Show Spoiler +
for i = 0 to 640
for j = 0 to 480
setpixel(i,j)
next
next

makes everything so slow. no matter of fps. I am just an amateuer, so please give some insight what you think i should do and what language is suitable. I want to do things from scratch (if possible). if i just could make the above loop work i would be happy. I though about C++ rather than Java for my purposes and interest but what about C# ?
ShAsTa
Profile Joined November 2002
Belgium2841 Posts
Last Edited: 2013-09-22 01:23:55
September 22 2013 01:18 GMT
#7136
On September 22 2013 09:32 bypLy wrote:
i am trying to build a 3d engine from scratch in an semi professional language (GL Basic). first i tried with vector matrix and z buffering but then i switched to ray casting style (doom)
the problem i always encounter is that at a certain point the performance goes rapidly down during rendering. a loop like:
+ Show Spoiler +
for i = 0 to 640
for j = 0 to 480
setpixel(i,j)
next
next

makes everything so slow. no matter of fps. I am just an amateuer, so please give some insight what you think i should do and what language is suitable. I want to do things from scratch (if possible). if i just could make the above loop work i would be happy. I though about C++ rather than Java for my purposes and interest but what about C# ?

Ray casting (tracing) is always gonna be slow, especially if you have a complex scene. Changing language isn't going to make a big difference. There are a lot techniques to speed things; boundings boxes/spheres, trees, parallelization, ...
You should figure out where exactly your program is spending a lot of time and try to improve that.
If we hit that bull's eye, the rest of the dominoes will fall like a house of cards. Checkmate.
bypLy
Profile Joined June 2013
757 Posts
September 22 2013 13:49 GMT
#7137
yes there can be many ways to optimize a programm. But even when i have no programm at all besides the for next loop containing the rendering of 640*480 pixels, the performance goes down. The points are not even calculated !!

this cant be i think. My PC is constantly rendering pixels even much more than 640*480. Why does the performance go down in this BASIC dialect i am using?
Rollin
Profile Joined March 2011
Australia1552 Posts
September 22 2013 13:53 GMT
#7138
Probably because we don't SW render these days, we batchout draw calls to the GPU with shaders/textures whatever.

Also relevant: http://scientificninja.com/blog/write-games-not-engines (AKA how every great game engine was made).
Throw off those chains of reason, and your prison disappears. | Check your posting frequency timeline: http://www.teamliquid.net/mytlnet/post_activity_img.php
ddengster
Profile Blog Joined January 2009
Singapore129 Posts
Last Edited: 2013-09-22 14:41:39
September 22 2013 14:40 GMT
#7139
On September 22 2013 22:49 bypLy wrote:
yes there can be many ways to optimize a programm. But even when i have no programm at all besides the for next loop containing the rendering of 640*480 pixels, the performance goes down. The points are not even calculated !!

this cant be i think. My PC is constantly rendering pixels even much more than 640*480. Why does the performance go down in this BASIC dialect i am using?


You gotta realize that even setPixel() has a performance overhead. Your method of drawing things on screen is called Software Rasterization. What games (and in general anything to do with graphics) use these days is the same rasterization process, but done in hardware(your graphics cards). All they require you to do is to send triangles, and they will set the appropriate pixels for you.

In general you should use one of the graphics APIs OpenGL and DirectX to accomplish what you trying to do. If say, for the sake of learning, you're willing to dig deeper then go ahead and write a software rasterizer; but be warned, it's a ton of math to go through.
Check out NEO Impossible Bosses, RTS-MOBA boss rush at http://neoimpossiblebosses.coder-ddeng.com
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
September 22 2013 22:35 GMT
#7140
On September 22 2013 23:40 ddengster wrote:
Show nested quote +
On September 22 2013 22:49 bypLy wrote:
yes there can be many ways to optimize a programm. But even when i have no programm at all besides the for next loop containing the rendering of 640*480 pixels, the performance goes down. The points are not even calculated !!

this cant be i think. My PC is constantly rendering pixels even much more than 640*480. Why does the performance go down in this BASIC dialect i am using?


You gotta realize that even setPixel() has a performance overhead. Your method of drawing things on screen is called Software Rasterization. What games (and in general anything to do with graphics) use these days is the same rasterization process, but done in hardware(your graphics cards). All they require you to do is to send triangles, and they will set the appropriate pixels for you.

In general you should use one of the graphics APIs OpenGL and DirectX to accomplish what you trying to do. If say, for the sake of learning, you're willing to dig deeper then go ahead and write a software rasterizer; but be warned, it's a ton of math to go through.

Pretty accurate advice here. Although, I've done the math myself and it isn't too bad. However, the math is quite hard to find good resources for; creating a 3D pipeline from scratch with only a SetPixel function isn't really something I would ever want to learn from rag-tag internet resources.
Prev 1 355 356 357 358 359 1031 Next
Please log in or register to reply.
Live Events Refresh
SC Evo League
12:00
S2 Championship: Ro16 Day 2
SteadfastSC86
EnkiAlexander 35
IntoTheiNu 13
IndyStarCraft 0
Liquipedia
WardiTV Summer Champion…
11:00
Playoffs Day 1
NightMare vs Zoun
Clem vs MaxPax
WardiTV943
Liquipedia
Sparkling Tuna Cup
10:00
Weekly #103
Solar vs ShoWTimELIVE!
ByuN vs TBD
CranKy Ducklings351
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Rex 143
ProTech93
BRAT_OK 87
SteadfastSC 86
IndyStarCraft 0
StarCraft: Brood War
Britney 45442
Larva 901
Killer 381
Hyun 325
Mini 286
Last 279
Hyuk 266
ggaemo 235
Pusan 234
Rush 233
[ Show more ]
firebathero 211
PianO 160
Mind 132
soO 41
Free 22
Sacsri 15
Noble 14
HiyA 11
Dota 2
Gorgc10645
qojqva1528
XcaliburYe319
Pyrionflax220
Fuzer 144
League of Legends
Dendi787
Counter-Strike
summit1g9354
olofmeister1869
Super Smash Bros
Mew2King58
Heroes of the Storm
Khaldor219
Other Games
singsing2024
B2W.Neo1177
byalli210
RotterdaM177
KnowMe58
rGuardiaN19
Organizations
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• Reevou 9
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• C_a_k_e 2849
• WagamamaTV458
League of Legends
• Nemesis4704
• Jankos2632
Upcoming Events
Chat StarLeague
2h 31m
Razz vs Julia
StRyKeR vs ZZZero
Semih vs TBD
Replay Cast
10h 31m
Afreeca Starleague
20h 31m
Queen vs HyuN
EffOrt vs Calm
Wardi Open
21h 31m
RotterdaM Event
1d 1h
Replay Cast
1d 10h
Afreeca Starleague
1d 20h
Rush vs TBD
Jaedong vs Mong
WardiTV Summer Champion…
1d 21h
PiGosaur Monday
2 days
Afreeca Starleague
2 days
herO vs TBD
Royal vs Barracks
[ Show More ]
Replay Cast
3 days
The PondCast
3 days
WardiTV Summer Champion…
3 days
Replay Cast
4 days
LiuLi Cup
4 days
Cosmonarchy
5 days
OyAji vs Sziky
Sziky vs WolFix
WolFix vs OyAji
BSL Team Wars
5 days
Team Hawk vs Team Dewalt
BSL Team Wars
5 days
Team Hawk vs Team Bonyth
SC Evo League
5 days
[BSL 2025] Weekly
6 days
SC Evo League
6 days
Liquipedia Results

Completed

Jiahua Invitational
uThermal 2v2 Main Event
HCC Europe

Ongoing

Copa Latinoamericana 4
BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Qualifiers
ASL Season 20
CSL Season 18: Qualifier 1
Acropolis #4 - TS1
CSLAN 3
SEL Season 2 Championship
WardiTV Summer 2025
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025

Upcoming

CSL Season 18: Qualifier 2
CSL 2025 AUTUMN (S18)
LASL Season 20
BSL Season 21
BSL 21 Team A
Chzzk MurlocKing SC1 vs SC2 Cup #2
RSL Revival: Season 2
Maestros of the Game
EC S1
Sisters' Call Cup
IEM Chengdu 2025
PGL Masters Bucharest 2025
MESA Nomadic Masters Fall
Thunderpick World Champ.
CS Asia Championships 2025
Roobet Cup 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.