• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

usea

Member
d[-_-]b;43055737 said:
need a little help with refactoring, essentially killing my ugly/spaghetti code
Code:
lManga = new Manga();
url = new URL(ele.get(i).attr("abs:href"));
lManga.setTitle(ele.get(i).text().replaceAll("\"", "").replace("'", ""));
lManga.setIndexLink(url.toString());
System.out.println(lManga.getTitle());
Document docdata2 = Jsoup.parse(url, 5000);
String ogImage = getMetaTag(docdata2, "og:image");
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(ogImage);
if (m.find()) {
	lManga.setID(Integer.valueOf(m.group()));
}
What techniques do you guys use...
What is the code supposed to be doing? Some code is obviously missing, since you're assigning to variables that aren't declared in the code snippet (url, lManga). Are they class members? We need more context to provide any help. It can't be reorganized without a more complete picture.

As for your question, just follow the SOLID principles. Basically, don't just throw a bunch of code into random places. A class should be responsible for one logical thing. A method should only do one thing, and its name should clearly describe what that one thing is. You should make use of composition when using other classes. This just means that if a class needs to do something that is the responsibility of another class, it should take an instance of that class in its constructor. For example, a ConfigurationParser class needs to validate the configuration, via a ConfigurationValidator class. It should just take an instance of ConfigurationValidator in its constructor.

A lot of this is overkill for very small projects. It's mostly about separating your concerns and maintaining a well-organized project. Some rules of thumb are like, is your method more than ~7-10 lines? (this number varies depending on who you ask), then it's probably doing more than one thing. Are you having trouble naming a method without using the word "and"? It's probably doing more than one thing.

Sorry if I rambled a bit. But if you post more of your code I'm sure people would be happy to give their opinions on how it could be refactored.
 

mltplkxr

Member
I'm starting off my first internship as a Java programmer (web automation, TestNG so far) and was wondering if you guys could recommend some books I could read on my 1+ hr. train ride to the office. I'm already into reading Effective Java, but some stuff isn't sticking as well as I'd like (usually I can get almost everything to stick w/o actually implementing it). I haven't had any work experience, but I think it I did pretty good/great throughout college. I think the best way to describe my situation is that I'm adept in the core mechanics of Java, but in the dark on various APIs, frameworks, etc. I really want to excel and I think it's within the realm of possibility.

Anything you guys throw out there I'll probably pick up off Amazon. I just found this thread, but I'm enjoying reading it so far. Hopefully I can contribute in the future.

Thanks.

edit: These are some I was looking at:

Java Complete Reference 8e by Oracle

Java in a Nutshell 5e (O'reilly) << from 2005...

It's hard to recommend any book because the API is HUGE. Depending on the job you get, there are parts you will use a lot and others you won't use at all. And that's without talking about Java EE and any other framework or tool that you'll end up using in your day to day.

If you had to focus on one important area of the core JDK, I'd recommend focusing on the Collections API. I can't underestimate the importance of mastering the different data structures the utility methods of the Collections and Arrays classes. Furthermore, it will come in handy regardless of the framework or tool you will use. O'Reilly put out Java Generics and Collections a long time ago http://shop.oreilly.com/product/9780596527754.do but it should still be relevant.

Effective Java (2nd Edition!) is an essential book but it will really start to stick once you have some experience developing some API's and application. I would suggest to memorize a general idea of the table of contents and to come back to the book when you have a question like: "Ok, I know how to implement equals() but what's really the best way to do it?" or "I have this compareTo() method to implement, I wonder how to write a really good one? ". Or put it aside and focus on just programming right now and come back to it once you've made enough mistakes : ).

If you want to specialize in Java, instead of reading through the reference books you cited (which are not really made to be read from cover to cover), you should go through one of the certification prep books and get your Java programmer cert. You'll achieve the same goal of going over the core API in depth and you'll be one step away from getting a cert to boot.

A final recommendation for a general book would be a book on patterns. Some of the API will make a lot more sense once you understand the patterns behind them.
 
I just wanna say, after using C# 3.5+ for the least two years, going back to Java feels to primitive(for lack of a better term).

Oracle really needs to step up their game already.

I know lambdas, LINQ, etc. is all syntactical sugar, but it makes a lot of things easier and less time consuming.
 

hateradio

The Most Dangerous Yes Man
What is the code supposed to be doing? Some code is obviously missing, since you're assigning to variables that aren't declared in the code snippet (url, lManga). Are they class members? We need more context to provide any help. It can't be reorganized without a more complete picture.
From what we can see, all it's doing is creating a new Manga object (lManga) and setting a title, index link, and if there's an image in the parsed Jsoup output that matches \\d+, it also ads an ID.

I'd probably remove the docdata2 stuff, unless it's used for something else, and remove all the image stuff. That would go into it's own function/method. The pattern could be a property of a class, I think. So that you don't have to compile it every time you call the method that tests the image's id.

In the end, it could look like this, where you're just setting the manga's properties.

Code:
# this is a func/method; Title, URL, and ID are being passed to it as params

lManga = new Manga();
lManga.setTitle(title);
lManga.setIndexLink(url);
if (id) {
	lManga.setID(id);
}
 

Croc

Banned
Okay so I'm super new to programming; I'm just trying to teach myself some C++. Right now I'm just messing around in Xcode and I really don't know what I'm doing at all. I'm just trying to follow along in a book and I'm doing all right so far. Right now in the book it's just having me do a bunch of small programs to see how different things work. My question is when I want to start a new small program, do I have to start an entirely new project each time or can I do something more quickly from the menus or within an existing project?
 

d[-_-]b

Banned
What is the code supposed to be doing? Some code is obviously missing, since you're assigning to variables that aren't declared in the code snippet (url, lManga). Are they class members? We need more context to provide any help. It can't be reorganized without a more complete picture.

As for your question, just follow the SOLID principles. Basically, don't just throw a bunch of code into random places. A class should be responsible for one logical thing. A method should only do one thing, and its name should clearly describe what that one thing is. You should make use of composition when using other classes. This just means that if a class needs to do something that is the responsibility of another class, it should take an instance of that class in its constructor. For example, a ConfigurationParser class needs to validate the configuration, via a ConfigurationValidator class. It should just take an instance of ConfigurationValidator in its constructor.

A lot of this is overkill for very small projects. It's mostly about separating your concerns and maintaining a well-organized project. Some rules of thumb are like, is your method more than ~7-10 lines? (this number varies depending on who you ask), then it's probably doing more than one thing. Are you having trouble naming a method without using the word "and"? It's probably doing more than one thing.

Sorry if I rambled a bit. But if you post more of your code I'm sure people would be happy to give their opinions on how it could be refactored.
Sure, sorry I was just giving of an example of how I code, I suck at this whole practical approach, tried the whole divide and conquer but I suck at tying things together, I try to get a functional piece of code first and work my way from there,
Code:
		public static void main(String[] args) throws Exception {
		URL urldata = new URL("http://www.mangahere.com/mangalist/");
		Document docdata = Jsoup.parse(urldata, 5000);
		Elements ele = docdata.select("div[class=list_manga]").select("li")
				.select("a");

		ArrayList<Manga> lMangaList = new ArrayList<Manga>();

		URL url;
		Manga lManga;
		Chapter lChapter;
		boolean bResume = false;
		for (int i = 0; i < ele.size(); i++) {
			if (ele.get(i).text().replaceAll("\"", "")
					.equalsIgnoreCase("Air Master"))
				bResume = true;
			if (bResume) {
				lManga = new Manga();
				url = new URL(ele.get(i).attr("abs:href"));
				lManga.setTitle(ele.get(i).text().replaceAll("\"", "")
						.replace("'", ""));
				lManga.setIndexLink(url.toString());
				System.out.println(lManga.getTitle());
				Document docdata2 = Jsoup.parse(url, 5000);
				String ogImage = getMetaTag(docdata2, "og:image");
				Pattern p = Pattern.compile("\\d+");
				Matcher m = p.matcher(ogImage);
				if (m.find()) {
					lManga.setID(Integer.valueOf(m.group()));
				}
				lManga.setCover(docdata2
						.select("div[class=manga_detail_top clearfix]")
						.select("img").attr("abs:src"));
				Elements ele2 = docdata2.select("div[class=detail_list]")
						.select("li").select("span[class=left]");
				for (int j = ele2.size() - 1; j >= 0; j--) {
					lChapter = new Chapter();
					lChapter.setTitle(ele2.get(j).text().replaceAll("\"", "")
							.replace("'", ""));
					Elements ele3 = ele2.get(j).select("a");
					String lCheckLink = ele3.attr("abs:href");
					// Parsing Actual Manga
					Page lPage;
					while (lCheckLink.contains("http://")) {
						url = new URL(lCheckLink);
						Document docdata3 = Jsoup.parse(url, 5000);
						Elements ele4 = docdata3
								.select("section[class=read_img]").select("a")
								.select("img");
						lCheckLink = ele4.attr("abs:src");
						if (lChapter.getID().isEmpty())
							lChapter.setID(lCheckLink.split("/")[6]);
						lPage = new Page();
						lPage.setLink(lCheckLink.split("/")[8]);
						Elements ele5 = docdata3.select("span[class=right]")
								.select("a[class=next_page]");
						lCheckLink = ele5.attr("abs:href");
						lChapter.getPages().add(lPage);
					}
					lManga.getChapters().add(lChapter);
				}
		}
	}

From what we can see, all it's doing is creating a new Manga object (lManga) and setting a title, index link, and if there's an image in the parsed Jsoup output that matches \\d+, it also ads an ID.

I'd probably remove the docdata2 stuff, unless it's used for something else, and remove all the image stuff. That would go into it's own function/method. The pattern could be a property of a class, I think. So that you don't have to compile it every time you call the method that tests the image's id.

In the end, it could look like this, where you're just setting the manga's properties.

Code:
# this is a func/method; Title, URL, and ID are being passed to it as params

lManga = new Manga();
lManga.setTitle(title);
lManga.setIndexLink(url);
if (id) {
	lManga.setID(id);
}

Thanks practically the basic idea

I was hoping to get a better idea going forward, trying to be a better programmer in a sense, I look at some of my projects like months after and have trouble recognizing what I was trying to do, try to use Hungarian notation to make it a bit easier, for myself, m -> members, p -> parameters, l -> local variables before there names but sometimes i'm inconsistent when i'm trying to get it to work.
 

hateradio

The Most Dangerous Yes Man
I think you should read a book on refactoring and OO schemes. Like someone previously stated, SOLID is what you should look for.

This is a simple example of code you can remove.

Code:
boolean bResume = false;
if (ele.get(i).text().replaceAll("\"", "")
					.equalsIgnoreCase("Air Master"))
				bResume = true;
			if (bResume) {
                        [stuff]

Since bResume is only used there, remove it and the if and only use the first one.

Code:
if (ele.get(i).text().replaceAll("\"", "")
        .equalsIgnoreCase("Air Master")) {
            [stuff]

Broadly, I'd suggest breaking up code by the blocks you have. Wherever you have a loop or an if or w/e, think about cutting it and placing it into its own function/method.

Eg

Code:
for(i = 0; i < length; i++) {
  handleElement(element(i));
}

handleElement would then take an element as a parameter (and instead of ele(i).text() you'd use element.text() or whatever parameter name you use).

If it were part of a class, docdata and other variables could be accessed as instance or static variables within the method, otherwise you'd also have to pass it as a parameter.
 
d[-_-]b;43060440 said:
Sure, sorry I was just giving of an example of how I code, I suck at this whole practical approach, tried the whole divide and conquer but I suck at tying things together, I try to get a functional piece of code first and work my way from there

I concur with everything usea said. That code is doing way too much. You would indeed be well served to find a resource like Clean Code and Agile: Patterns, Principles, and Practices from Robert C. Martin.

First rule of functions is that functions should be small. Second rule of functions is that they should be smaller than that. ;)

As a quick suggestion, think of it like every level of indent could and perhaps should be a function. Complex conditional? Function. Multiple steps in an algorithm? Describe those steps with functions. Give them all good names. Some of those smaller functions would indeed make sense to be refactored out into their own classes, as the idea is indeed something that can or should exist separately. For example, think of function A. Out of function A, you extract function B. Function A now looks clean, but function B now needs work. You extract function C. Function A doesn't need C. Function A will never call C. C is just further implementation detail for B. Hmm, perhaps this reveals another class living in your code! That class could be Function B, which calls C, or it could be C, which might also end up being broken down into its own smaller functions or even smaller classes.
 

d[-_-]b

Banned
I concur with everything usea said. That code is doing way too much. You would indeed be well served to find a resource like Clean Code and Agile: Patterns, Principles, and Practices from Robert C. Martin.

First rule of functions is that functions should be small. Second rule of functions is that they should be smaller than that. ;)

As a quick suggestion, think of it like every level of indent could and perhaps should be a function. Complex conditional? Function. Multiple steps in an algorithm? Describe those steps with functions. Give them all good names. Some of those smaller functions would indeed make sense to be refactored out into their own classes, as the idea is indeed something that can or should exist separately. For example, think of function A. Out of function A, you extract function B. Function A now looks clean, but function B now needs work. You extract function C. Function A doesn't need C. Function A will never call C. C is just further implementation detail for B. Hmm, perhaps this reveals another class living in your code! That class could be Function B, which calls C, or it could be C, which might also end up being broken down into its own smaller functions or even smaller classes.
Thanks guys, I appreciate the straight-forward criticism, as for buying books pretty much broke right now as a college student.
Couple of semesters ago, worked on Mall Management Project (Software Engineering Course)
PeMeD.png
Approach was to work from top down
- Mall -> Consist of Stores (Store Management) -> Consists of Products (Product Management) -> Product Details
I understand that I need to use the divide and conquer approach but sometimes it doesn't come naturally, using an arbitrary limit might help (line counting), but to be able to take out redundancies in my code is a little harder.
 
I'm having some trouble with Java again.

The program is supposed to convert your weight to a weight on a different planet. Im having trouble on how to specify which planet your picking (in this case its The Sun or Saturn). I need to use nested Switch statements and I thought this would work but errors are occurring at the case "letter" lines. Can anyone tell me what I am doing wrong?

The error message is a Type mismatch: Cannot convers String to Char.

Code:
public static void getChoice(int weight) throws IOException
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String response;
		System.out.println("On which planet would you like to know your body weight?");
		response = in.readLine();
		switch (response.charAt(0))
		{
		case "s":
		case "S":
			switch (response.charAt(1))
			{
			case "u":
			case "U":
				System.out.println("Your weight on the Sun would be " + (weight*27.94));
			case "a":
			case "A":
				System.out.println("Your weight on Saturn would be " + (weight*1.15));
			}//end Sun or Saturn

If the first character given to the program is S then it moves to the next switch statement, then it looks at the second letter to see it it is a 'u' or 'a'. If I input 'Su' then it will choose the first case, if the first two letters are 'Sa' then it will go with the second case statement. What am I doing wrong?
 

Zeppelin

Member
I'm having some trouble with Java again.

The program is supposed to convert your weight to a weight on a different planet. Im having trouble on how to specify which planet your picking (in this case its The Sun or Saturn). I need to use nested Switch statements and I thought this would work but errors are occurring at the case "letter" lines. Can anyone tell me what I am doing wrong?

The error message is a Type mismatch: Cannot convers String to Char.

Code:
public static void getChoice(int weight) throws IOException
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String response;
		System.out.println("On which planet would you like to know your body weight?");
		response = in.readLine();
		switch (response.charAt(0))
		{
		case "s":
		case "S":
			switch (response.charAt(1))
			{
			case "u":
			case "U":
				System.out.println("Your weight on the Sun would be " + (weight*27.94));
			case "a":
			case "A":
				System.out.println("Your weight on Saturn would be " + (weight*1.15));
			}//end Sun or Saturn

If the first character given to the program is S then it moves to the next switch statement, then it looks at the second letter to see it it is a 'u' or 'a'. If I input 'Su' then it will choose the first case, if the first two letters are 'Sa' then it will go with the second case statement. What am I doing wrong?

Now I don't know Java that well, but... You're trying to compare a char to a string. Instead of using double quotes (") in your switch, use single quotes ('). E.g. case 's':

Or just use some kind of string comparison function instead of the whole nested switches thing.
 
Now I don't know Java that well, but... You're trying to compare a char to a string. Instead of using double quotes (") in your switch, use single quotes ('). E.g. case 's':

Or just use some kind of string comparison function instead of the whole nested switches thing.

I think you're trying to compare with strings "x" (double quotes) while you should be comparing with a char 'x' (single quotes)


Wow, it was really that easy. Thanks! I guess I'm just too tired to write this program...
 

Anustart

Member
Looking for some advice gaf. I have a project for university i have to do.

What it is is we have the freedom of choice to do our project on anything based on c#. I really want to do something special, but having trouble picking something.

It's an advanced course, so I'm quite proficient in the foundation of c#, but the aim is to broaden our own horizon, teach other students and to have fun.

Anyone have any ideas for what i could base such a project on? I'm not looking for help in the work, just a bit of direction from some of you more skilled coders.
 

CrunchyB

Member
Looking for some advice gaf. I have a project for university i have to do.

What it is is we have the freedom of choice to do our project on anything based on c#. I really want to do something special, but having trouble picking something.

It's an advanced course, so I'm quite proficient in the foundation of c#, but the aim is to broaden our own horizon, teach other students and to have fun.

Anyone have any ideas for what i could base such a project on? I'm not looking for help in the work, just a bit of direction from some of you more skilled coders.

How about a program which does facial recognition? There are libraries and examples you can use like http://www.codeproject.com/Articles/239849/Multiple-face-detection-and-recognition-in-real-ti.

Once you can read video from a webcam (shouldn't be too hard) you can do some augmented reality stuff, like automatically draw glasses or mustaches on people.

You can make your program architecturally interesting as well, design a plug-in interface for your system so you can use different image detection libraries or effects next to each other. Maybe even design XML to define these image effects.

Extra stuff which might be interesting; make it multi-platform (use Mono), add Unit Tests and a Regression Testing system.
 

Anustart

Member
How about a program which does facial recognition? There are libraries and examples you can use like http://www.codeproject.com/Articles/239849/Multiple-face-detection-and-recognition-in-real-ti.

Once you can read video from a webcam (shouldn't be too hard) you can do some augmented reality stuff, like automatically draw glasses or mustaches on people.

You can make your program architecturally interesting as well, design a plug-in interface for your system so you can use different image detection libraries or effects next to each other. Maybe even design XML to define these image effects.

Extra stuff which might be interesting; make it multi-platform (use Mono), add Unit Tests and a Regression Testing system.

Thank you very much for this idea! I love it and just fired off an email to my professor to get the go ahead to begin work. This is much better than the ideas that I had been thinking of, and will make for a very interesting educational presentation for my fellow classmates. Gracias!
 

Haly

One day I realized that sadness is just another word for not enough coffee.
There isn't a general web dev thread, not that I know of anyway.

A lot of people ask html/php questions so I don't think anyone will mind.
 

Seanbob11

Member
Does anyone have any experience in Graphics2D and drawing text? This is my first semester doing Java so something easy to understand would be helpful. Anything on drawing stars in an arch too? I can draw the star by making a polygon I just need to know how to make them arrange in an arch. Thanks.
 

Jobiensis

Member
I can't find a text editor I like for everything.

I don't understand how 'programming' text editors can have such bad find in files support.

I've used TextPad for years, but the lack of UTF-16 support is starting to cause me lots of problems.

I tried Notepad++, but find in files basically freezes the app until it is done. I's a shame because it does most other things really well.

Sublime, but the find in files just dumps grep results in a window, you can't go through the search results.

Any recommendations?

Text editor with good unicode support, syntax highlighting and find in files functionality. It'd be nice to have both OSX and Windows versions, but Windows is the most important.
 

Flek

Banned
There isn't a general web dev thread, not that I know of anyway.

A lot of people ask html/php questions so I don't think anyone will mind.


ok awesome - so my question:

i just learned a bit about HTML 5 and tags like <adress> or <cite> and i don´t really understand WHY i should use them. Why use adress when i can simply use <i> ?
 
ok awesome - so my question:

i just learned a bit about HTML 5 and tags like <adress> or <cite> and i don´t really understand WHY i should use them. Why use adress when i can simply use <i> ?

<i> just italicizes text. This is bad, even in HTML4.

In general, the goal for how you organize your site:
HTML - Define what your content is.
CSS - Define how your content looks.

Due to deficiencies in CSS, it won't be possible to always keep the two separate (CSS was built for styling, not for layout; you will always have markup in there purely for structural purposes when laying out content), but it should be a goal in general.

The new tags are theoretically nice because it gives the browser and other interpreters of the document more visiblility into what the content in your document actually represents (though I have never actually used any of the new HTML5 tags except for video and tooling around with canvas).
 

CrunchyB

Member
Does anyone have any experience in Graphics2D and drawing text? This is my first semester doing Java so something easy to understand would be helpful. Anything on drawing stars in an arch too? I can draw the star by making a polygon I just need to know how to make them arrange in an arch. Thanks.

You need to describe an arch, you can use Math.sin() for this. Something like:

Code:
unsigned int nStars = 10;
double x;
for( unsigned int i = 0; i < nStars; i++ )
{
	x = i * ( Math.PI / nStars);
	drawStarAtLocation( x, Math.sin( x ) );
}
 

PistolGrip

sex vacation in Guam
Hey CompSci-Gaf

Can someone help me make this code smaller (Its Python btw):
Code:
items = []
for line in open('sample','r'):
    nums = line.split()
    items.extend(nums)

buckets = [0] * (int(max(items)) + 1)
for i in items: #    print 'item:',  i
    buckets[int(i)] += 1

for ind, i in enumerate(buckets):
    for j in range(0,i):
        print ind
 
ok awesome - so my question:

i just learned a bit about HTML 5 and tags like <adress> or <cite> and i don´t really understand WHY i should use them. Why use adress when i can simply use <i> ?
HTML like many markup languages was created to define the semantics of the document. H tags define headers. Strong shows emphasis. A div represents a division of the page. Input reflects some kind of input necessary.

Address, section, header, etc were added to improve semantic meaning.

Layout and style is still left to CSS or at least should be.
 
Sublime, but the find in files just dumps grep results in a window, you can't go through the search results.

If you choose the "use buffer" option (the button right next to "Find" in the search window) it'll put the results into a document window which you can then search through.

Sublime is perfectly named, it instantly became my favourite editor. I've converted quite a few of my co-workers to it.
 

usea

Member
If you choose the "use buffer" option (the button right next to "Find" in the search window) it'll put the results into a document window which you can then search through.

Sublime is perfectly named, it instantly became my favourite editor. I've converted quite a few of my co-workers to it.
It'd be OK if it were free. For the price, it's a rip-off.
 
It'd be OK if it were free. For the price, it's a rip-off.

It costs more than other editors (which are "free" but often rely on donations to support development), yes. However I don't agree it's overpriced at all and I've never heard that from any of my colleagues that switched to it either. The way I look at it is that $60 for a best-in-breed piece of software that took years to develop, a primary tool that you use for hours every day, and can install on as many machines as you like running any supported OS, is a bargain.

Text editor preference is incredibly personal and if you find one that clicks, it's worth its weight in gold IMHO. I realize that to you the value proposition isn't there, but for me and many others it's cheap at the price.
 

Slavik81

Member
It costs more than other editors (which are "free" but often rely on donations to support development), yes. However I don't agree it's overpriced at all and I've never heard that from any of my colleagues that switched to it either. The way I look at it is that $60 for a best-in-breed piece of software that took years to develop, a primary tool that you use for hours every day, and can install on as many machines as you like running any supported OS, is a bargain.

Text editor preference is incredibly personal and if you find one that clicks, it's worth its weight in gold IMHO. I realize that to you the value proposition isn't there, but for me and many others it's cheap at the price.

It does indeed look great, and it is very cheap. Unfortunately, there is exactly one reason why I don't use Sublime.

Code:
class MyClass;
MyClass x;
 ^----- Sublime has no idea what MyClass is.
If it was just ever so slightly smarter at syntax highlighting, I'd switch in an instant. I might pay triple its current price and buy 2 copies if it had that sort of intelligence...

I know you can get vim to work with that sort of magic. Alas, there's no syntax-highlighting API for Sublime, so third-parties like SublimeClang can't fill the gap.
 
About code structuring:

I remember initially (like most of us) coding huge amorphous chunks of code that seemingly tried to do everything and were a nightmare to read and maintain.

Afterwards, I went to the other extreme, and adopted the "functions should be small and focused" approach, where I moved everything that could (conceptually and functionally) be isolated into its own function.

Nowadays, I've settled down about halfway (or 40/60) between the two. Basically now I only make new functions if I'm (attempting to) optimize something, or if I notice that I'm copy pasting the same code around more than once (and even then there are exceptions).

I've just noticed that when debugging or extending some code (i.e. re-learning it to some degree) the overhead of jumping around all over the codebase to see what all those small functions are trying to do just isn't worth it. I try to keep my functions about 1 to 1.5 pages long (MAX) in my IDE now, and this has tremendously improved readability for me.
 

usea

Member
It costs more than other editors (which are "free" but often rely on donations to support development), yes. However I don't agree it's overpriced at all and I've never heard that from any of my colleagues that switched to it either. The way I look at it is that $60 for a best-in-breed piece of software that took years to develop, a primary tool that you use for hours every day, and can install on as many machines as you like running any supported OS, is a bargain.

Text editor preference is incredibly personal and if you find one that clicks, it's worth its weight in gold IMHO. I realize that to you the value proposition isn't there, but for me and many others it's cheap at the price.
Yeah I agree. But I look at other products like LINQPad which imo is better than Sublime (although definitely less robust since it's scope is limited to a few languages) and only costs $40.

I use Sublime for Go, and I think it's OK but as somebody who uses Visual Studio all day at work it's kind of pathetic in comparison. Granted I'm also not very skilled with it, and I get the impression that GoSublime does a lot of stuff in unusual ways.

About code structuring:

I remember initially (like most of us) coding huge amorphous chunks of code that seemingly tried to do everything and were a nightmare to read and maintain.

Afterwards, I went to the other extreme, and adopted the "functions should be small and focused" approach, where I moved everything that could (conceptually and functionally) be isolated into its own function.

Nowadays, I've settled down about halfway (or 40/60) between the two. Basically now I only make new functions if I'm (attempting to) optimize something, or if I notice that I'm copy pasting the same code around more than once (and even then there are exceptions).

I've just noticed that when debugging or extending some code (i.e. re-learning it to some degree) the overhead of jumping around all over the codebase to see what all those small functions are trying to do just isn't worth it. I try to keep my functions about 1 to 1.5 pages long (MAX) in my IDE now, and this has tremendously improved readability for me.
Yikes! I don't know how big a page is for you, but that is really unwieldy imo. Do you work on projects with other people, who have to read and understand your code, and fix bugs in it? BTW most IDEs have very handy shortcuts for navigating to code quickly. Usually there will be a key that will bring you directly to the implementation of some method, and hopefully a way to find every place that some method, class, property, etc is used. Also you can usually navigate directly to some file by typing a portion of its name.

Some benefits of having very small functions are
1) You can immediately tell at a glance everything that function is supposed to do. For example if its signature is something like:
Code:
public IList<Student> GetAllStudents()
then you can immediately tell what this method is supposed to do. If you look at the code and it seems to be doing other things too, like creating new students or changing a student's class schedule, then something is wrong. It's very important to be able to glance at code and know what it is supposed to be doing. Good names are important for this too.
2) Code that does one thing is not mingling with code that does another thing. Once your loops and conditionals and local variables are getting all mixed together, if you have to change something about one part then the likelihood of that change unintentionally affecting other parts goes way up. For example if your GetAllStudents() method also changes a student's schedule, then suddenly you decide you don't need to get all students, only upperclassmen, then that change might screw up some students' schedules. That's craziness, they shouldn't be related at all.
 

DTKT

Member
So, I'm trying to write a little script in Python where it pulls an entire page HTML code and exports it to a text file. I have some basic experience in Borland and Java and I'm just starting C++ but we've never touched text files or any other kind of files. Python seemed like the natural choice for a quick and dirty script but I might be just unaware of the intricacies of the other languages.

Most of what I have is cobbled code from a couple of tutorials.

So for the first part, I have :

import shutil
import os
import time
import datetime
import math
import urllib
from array import array

filehandle = urllib.urlopen('URL')
myFile = open('file.txt','w')

for lines in filehandle.readlines():
print lines
myFile.write(lines)

myFile.close()
filehandle.close()

This part works great! Creates a neat little text file with the exported text inside it. Quite exciting.

The next part seems to be a bit more tricky. Basically, the information I need to extract is scattered throughout the document. My guess is that I need to find something that's constant and that let's me pinpoint on which line the information is. I can do that! I can look for a specific string and that would let me know on which line the information is. The issue is that I need something that's placed after what I told the program to find.

Basically:

"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7070"
"Blablablablalba"
"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7075"
"Blablablablalba"
"Blablablablalba"
"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170"
"Blablablablalba"
"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170"
"Blablablablalba"

I can search the document for "HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY ", this would tell me which lines have the info I need. But, is there a way to specify which part of the line I want? Ideally, I would just want to extract the numbers.

I don't have much so far, but it's a start:

import re

infile = open("ImportedStuff.txt","r")
PlayerCout = open("NumbersList.txt","w")

for line in infile:
if re.match("TEXT I'M Looking for", line):
print >> NumbersList, line,

That would print the entire line. Which seems to be a good starting point. I guess that, if I have the entire line, I can just put every char in an array, remove the entire length of the "HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY " and just keep the rest.

Any hints, tips?
 
I think I've realized why I'm so hesitant to switch from Java to C. It's because I'm afraid of using memory and memory management.

For some reason, I don't like allocating large chunks of RAM, even for something as simple as a program which converts a level/map for a game I'm making to a png format. Instead of doing the sensible thing and loading the whole level into memory, I load one line, then write one line of the png, etc.

Then when I load the level for my game, even though it's just 1-2 KB, I stream the level from disk because I'm afraid to load it all to RAM.

Then I worry about other little things like fragmentation resulting from freeing mallocs, and I know I'm overthinking it... lol. Maybe I've become too used to Java's garbage collector...
 
Anyone else taking a course on coursera? I just tried the Python one myself and it was swell. I've never heard of CodeSkulptor, but it sorta reminded me of Zembly. Deadline for signups is tomorrow and the first quiz is due very soon after that. They basically provide you a lot of video lectures (grouped in weeks), then you can take quizzes. There are also projects you do. The course load is supposedly around 7-9 hours per week.

It's tailored for people really new to programming so I'd recommend it based on what I've done for the course so far.
 

r1chard

Member
Hey CompSci-Gaf

Can someone help me make this code smaller (Its Python btw):
Code:
items = []
for line in open('sample','r'):
    nums = line.split()
    items.extend(nums)

buckets = [0] * (int(max(items)) + 1)
for i in items: #    print 'item:',  i
    buckets[int(i)] += 1

for ind, i in enumerate(buckets):
    for j in range(0,i):
        print ind
I presume we're doing some homework for you, so my late response will not help other than to hopefully enlighten ;-)

Your buckets should IMO be, in increasing order of preference, a dictionary, a defaultdict(int) or a Counter.

Code:
from collections import Counter
buckets = Counter()
for line in open('sample','r'):
    buckets.update(Counter(int(num) for num in line.split()))



Basically:

"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7070"
"Blablablablalba"
"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7075"
"Blablablablalba"
"Blablablablalba"
"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170"
"Blablablablalba"
"HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170"
"Blablablablalba"

I can search the document for "HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY ", this would tell me which lines have the info I need. But, is there a way to specify which part of the line I want? Ideally, I would just want to extract the numbers.

You could use regular expressions, or you could use my parse module (pip install parse):

Code:
>>> from parse import parse
>>> parse('HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY {:f}', "HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170")
<Result (60.717,) {}>
The ":f" part is optional - if you want a string instead of the float result then just lose it. If want to find all the instances in a file then:

Code:
>>> from parse import findall
>>> text = '''HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7070
... Blablablablalba
... HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7075
... Blablablablalba
... Blablablablalba
... HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170
... Blablablablalba
... HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY 60.7170
... Blablablablalba
... '''
>>> for r in findall('HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY {:f}', text):
...   print r[0]
... 
60.707
60.7075
60.717
60.717

That would print the entire line. Which seems to be a good starting point. I guess that, if I have the entire line, I can just put every char in an array, remove the entire length of the "HELLO THIS IS POTATO WHAT A BEAUTIFUL DAY " and just keep the rest.
To answer this problem directly: you'll want to use an RE group and then the MatchObject that re.match returns will have information about the match. Or just use parse; simple cases like this is what I designed it for :)
 

Nesotenso

Member
having indentation error in python project at code academy

Code:
def fizzCount(list):
	count = 0
      for names in list:
            if names =="fizz":
	            count+= 1
	        else:
	            count== 0
    return count

soda = ["fizz","soda","fizz","fizz"]  
print fizzCount(soda)

line 3 at start loop.

IndentationError: unindent does not match any outer indentation level

does IDLE let you look at tab/spaces where you are messing up.
 

mltplkxr

Member
I can't find a text editor I like for everything.

I don't understand how 'programming' text editors can have such bad find in files support.

I've used TextPad for years, but the lack of UTF-16 support is starting to cause me lots of problems.

I tried Notepad++, but find in files basically freezes the app until it is done. I's a shame because it does most other things really well.

Sublime, but the find in files just dumps grep results in a window, you can't go through the search results.

Any recommendations?

Text editor with good unicode support, syntax highlighting and find in files functionality. It'd be nice to have both OSX and Windows versions, but Windows is the most important.
TextPad was the shit! What a great text editor.
The only equivalent of Find in Files that I know of is in Eclipse, where you can do a search through all the files in a project or a whole workspace (a group of projects).
 

r1chard

Member
having indentation error in python project at code academy

Code:
def fizzCount(list):
	count = 0
      for names in list:
            if names =="fizz":
	            count+= 1
	        else:
	            count== 0
    return count

soda = ["fizz","soda","fizz","fizz"]  
print fizzCount(soda)
When pasted in here line 2 is clearly indented incorrectly. Hence line 3 unindents to a level not previously seen by the compiler.

It looks like the "count = 0" line is indented with a TAB and the rest of the code indented with a mixture of tabs spaces.

Python rule #1 (or close to): don't mix tabs and spaces.

does IDLE let you look at tab/spaces where you are messing up.
Sadly, it doesn't look like it. WTf.
 

Nesotenso

Member
When pasted in here line 2 is clearly indented incorrectly. Hence line 3 unindents to a level not previously seen by the compiler.

It looks like the "count = 0" line is indented with a TAB and the rest of the code indented with a mixture of tabs spaces.

Python rule #1 (or close to): don't mix tabs and spaces.


Sadly, it doesn't look like it. WTf.

fixed it on IDLE by select all- format- untabify region and selecting tab width.

really hate this tab/ space thing after using parentheses in C++/C
 

mltplkxr

Member
d[-_-]b;43083164 said:
Thanks guys, I appreciate the straight-forward criticism, as for buying books pretty much broke right now as a college student.
As a broke college student you should have access to a library. Get in touch with them and see if they have an account with O'Reilly's Safari. If they do, you'll have access to some of the best IT/Computer Science ebooks (like Code Complete ;).
 

r1chard

Member
fixed it on IDLE by select all- format- untabify region and selecting tab width.

really hate this tab/ space thing after using parentheses in C++/C
IDLE makes it much more difficult than it should be. A proper editor / IDE won't have this problem.

PyCharm is free to try. It's good.

Edit: try IDLEX - it's an added extras version of IDLE that includes such useful things in the editor as line numbers, tab highlighting, and so on.
 
so my friend came round yesterday and somehow in conversation it casually came up that our end of semester java assignment was due at 9am and not pm. Oh dear I says.

18 hours wrestling with RMI, learning to lovehate GridBagLayout, and scouring out masses of encrusted comments. handed it in on time and just a little bit slightly delirious now but of course can't sleep. To be blunt, I hurt, but damn if it wasn't kind of fun.
 

ferr

Member
so my friend came round yesterday and somehow in conversation it casually came up that our end of semester java assignment was due at 9am and not pm. Oh dear I says.

18 hours wrestling with RMI, learning to lovehate GridBagLayout, and scouring out masses of encrusted comments. handed it in on time and just a little bit slightly delirious now but of course can't sleep. To be blunt, I hurt, but damn if it wasn't kind of fun.

Those are the best ones. And the ones when you have the flu so you decide to make a SimCity rip-off at 3am is fun as well.
 

leroidys

Member
I have this assignment with a ton of bit twiddling puzzles, and this one has stumped me. We're supposed to write a isLessOrEqual function in C with the constraints that we can only use the operators ! ~ & ^ | + << >> and can't use a constant larger than 255 or any conditionals or loops.

It seems easy enough, and I came up with :

Code:
}
/* 
 * isLessOrEqual - if x <= y  then return 1, else return 0 
 *   Example: isLessOrEqual(4,5) = 1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 24
 *   Rating: 3
 */
int isLessOrEqual(int x, int y) {

	int result = ~y +1;

	result = x + result;


	result = (result >> 31) & 1;


  return result;
}
/*

but the function fails on (-2147483648, -2147483648), which I can't make a twos complement out of.
 

Tomat

Wanna hear a good joke? Waste your time helping me! LOL!
Anyone here familiar with programming for the M68K in EASY68k?

I'm getting a syntax error every time I try to use the unconditional branch BRA. BRA is a thing right? As in it actually exists.

I try something like BRA NEXT, but it doesn't seem to want to work.

*edit* Nevermind, got it working. Was something wrong with my labels.
 
Top Bottom