• 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

missile

Member
This book is great.

http://www.wired.com/gamelife/2009/03/racing-the-beam/

televisionscreen.png
Not having a framebuffer has invented some fundamental computer graphics
algorithms like for example real-time scan-conversion (a.k.a scan-line
rasterizing) which are even used today on framebuffer devices. The challenge
programming without a framebuffer is that you have to be cycle accurate.
Some of you may wonder why letters do have a lot of spacing in-between on
older graphics. The blank area is the time necessary to set up for the next
letter on the same scanline. One can even do such kind of programming today.
Use a simple microcontroller (one with at least 6MHz+ to drive the NTSC or PAL
signal) where one output pin is connected to two resistors (for 1 bit
graphics) to modulate the NTSC or PAL signal. The cool thing doing this is
that one can learn the fundamentals of video graphics accelerators. Here is
a page entirely dedicated to this; http://www.rickard.gunee.com/projects/.


For our German friends;
Unfortunately, there are only a few good technical C/C++ books at all. Many
standard books about C/C++ list miles of code and just talk, well, dummes
Zeug? xD But luckily, there are a few which are very, very good. Two of those
are the following one, written by Klaus Schmaranz.

41dAtZW50SL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU03_AA160_.jpg

Klaus Schmaranz, Titel: Softwareentwicklung in C, ISBN-10: 3540419586
http://www.amazon.de/dp/3540419586/

41ABkxe-AWL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU03_AA160_.jpg

Klaus Schmaranz, Titel: Softwareentwicklung in C++, ISBN-10: 3540443436
http://www.amazon.de/dp/3540443436/

If you go for real, these two books are a real blast! I would recommend starting
with the C book first. The insight you gain is enormously.

Well, if you have one and a half hour left, here is a good talk about C++11;
Day 1 Keynote - Bjarne Stroustrup: C++11 Style.


Edit:
Klaus Schmaranz has released the books to the public;
[pdf] Softwareentwicklung in C, and
[pdf] Softwareentwicklung in C++.
 

mltplkxr

Member
By useful I mean most used languages in the industry. I'm gonna graduate in a couple of days and really like to broaden my knowledge for finding a job as soon as possible. Nobody wants to hire a junior.

If you're looking to standout to recruiters, I'd suggest contributing to open source projects instead of learning new languages. Knowing a language is one thing but applying it in a "real world" context is a completely different ball game. By working on projects in use, you'll get a sense of that and you'll learn how to navigate a large code base. You'll also learn how to use a source code versioning system (like Git, Hg, SVN) in the context of a team, which is essential.

Like someone else said: a language is just a tool to get a job done. While learning a language is not always easy, the real complexity is in translating (business/human) requirements into a working application and resolving issues and performance problems that are a result of users using the application. This is a big part of working in software that I didn't learn in school IMHO. I hope your degree was better on that front.

Nevertheless, if you want to bolster your resume with a new language, do this:
1.determine the industry you want to work in.
2.identify the most popular languages or frameworks in that sphere,
3.try a few languages and see which ones you are comfortable with and those you aren't.

In short, take x number of languages then: pick one, spend an hour or two every day for a week, repeat. (This will give you lots to talk about in an interview too)

That's the idea behind a book called "Seven Languages in Seven Weeks". The choice of languages is a bit on the fringe side (Erlang, Prolog) and Bruce Tate is an opinionated author, but the idea is a very good one. There's something similar on Manning with Powershell in an Month of Lunches.
 

Victarion

Member
If you're looking to standout to recruiters, I'd suggest contributing to open source projects instead of learning new languages. Knowing a language is one thing but applying it in a "real world" context is a completely different ball game. By working on projects in use, you'll get a sense of that and you'll learn how to navigate a large code base. You'll also learn how to use a source code versioning system (like Git, Hg, SVN) in the context of a team, which is essential.

Like someone else said: a language is just a tool to get a job done. While learning a language is not always easy, the real complexity is in translating (business/human) requirements into a working application and resolving issues and performance problems that are a result of users using the application. This is a big part of working in software that I didn't learn in school IMHO. I hope your degree was better on that front.

Nevertheless, if you want to bolster your resume with a new language, do this:
1.determine the industry you want to work in.
2.identify the most popular languages or frameworks in that sphere,
3.try a few languages and see which ones you are comfortable with and those you aren't.

In short, take x number of languages then: pick one, spend an hour or two every day for a week, repeat. (This will give you lots to talk about in an interview too)

That's the idea behind a book called "Seven Languages in Seven Weeks". The choice of languages is a bit on the fringe side (Erlang, Prolog) and Bruce Tate is an opinionated author, but the idea is a very good one. There's something similar on Manning with Powershell in an Month of Lunches.

That sounds like a good idea. I'll look into it, thanks for the advise.
 

Milchjon

Member
For our German friends;
Unfortunately, there are only a few good technical C/C++ books at all. Many
standard books about C/C++ list miles of code and just talk, well, dummes
Zeug? xD But luckily, there are a few which are very, very good. Two of those
are the following one, written by Klaus Schmaranz.

41dAtZW50SL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU03_AA160_.jpg

Klaus Schmaranz, Titel: Softwareentwicklung in C, ISBN-10: 3540419586
http://www.amazon.de/dp/3540419586/

41ABkxe-AWL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU03_AA160_.jpg

Klaus Schmaranz, Titel: Softwareentwicklung in C++, ISBN-10: 3540443436
http://www.amazon.de/dp/3540443436/

If you go for real, these two books are a real blast! I would recommend starting
with the C book first. The insight you gain is enormously.

Well, if you have one and a half hour left, here is a good talk about C++11;
Day 1 Keynote - Bjarne Stroustrup: C++11 Style.


Edit:
Klaus Schmaranz has released the books to the public;
[pdf] Softwareentwicklung in C, and
[pdf] Softwareentwicklung in C++.

Thanks for those, will check them out.
 

Lathentar

Looking for Pants
What would be the most important languages to learn within the gaming industry?

Having a concrete knowledge of c and c++ is vital. You don't need a perfect grasp of some complex concepts such as template meta programming and anything in c++0x though, stuff like that will most likely not be relevant. Regardless of your focus you need to learn how to write and use 3d math libraries and the basic data structures including vectors, lists, maps, sets and hash tables. If you want to further impress a knowledge of spacial partitioning algorithms is very handy.

One thing I'm noticing more is knowledge of c# and similar languages are being desired as tools work is transitioning to these languages. So having that knowledge will be a plus.
 
Java Question.

The use of abstract and interface classes. I can understand the distinctions between them but can't quite fathom their uses. Why would I want to define a class that is incomplete or has partial implementation but needs to be completed later in another class?

Making a class and implement everything, making it complete makes more senses to me than the aforementioned. Because I know all I have to do is use them as I wish and not think about, completing it later.

Should I want to introduce new methods, it is not a problem, I can override or make a new class inheriting or copying another class.
 
Java Question.

The use of abstract and interface classes. I can understand the distinctions between them but can't quite fathom their uses. Why would I want to define a class that is incomplete or has partial implementation but needs to be completed later in another class?

Making a class and implement everything, making it complete makes more senses to me than the aforementioned. Because I know all I have to do is use them as I wish and not think about, completing it later.

Should I want to introduce new methods, it is not a problem, I can override or make a new class inheriting or copying another class.

Maybe this can clear up some of the confusion it helped my understand why it was useful to use an interface.
http://en.wikipedia.org/wiki/Strategy_pattern
 
For our German friends;
Unfortunately, there are only a few good technical C/C++ books at all. Many
standard books about C/C++ list miles of code and just talk, well, dummes
Zeug? xD But luckily, there are a few which are very, very good. Two of those
are the following one, written by Klaus Schmaranz.

41dAtZW50SL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU03_AA160_.jpg

Klaus Schmaranz, Titel: Softwareentwicklung in C, ISBN-10: 3540419586
http://www.amazon.de/dp/3540419586/

41ABkxe-AWL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU03_AA160_.jpg

Klaus Schmaranz, Titel: Softwareentwicklung in C++, ISBN-10: 3540443436
http://www.amazon.de/dp/3540443436/

If you go for real, these two books are a real blast! I would recommend starting
with the C book first. The insight you gain is enormously.

Well, if you have one and a half hour left, here is a good talk about C++11;
Day 1 Keynote - Bjarne Stroustrup: C++11 Style.


Edit:
Klaus Schmaranz has released the books to the public;
[pdf] Softwareentwicklung in C, and
[pdf] Softwareentwicklung in C++.

You really like them? I have both at home and did not find them very beginner friendly. Especially the C++ version which basicly assumes you are fluent with C more or less from the first book.
 

missile

Member
You really like them? I have both at home and did not find them very beginner friendly. Especially the C++ version which basicly assumes you are fluent with C more or less from the first book.
Define 'beginner friendly'. ;) Yes, the C version integrates into the C++
version quite nicely, which is, in this case, very good. Both books are
technically very sound. One of the key-features of these books is that they
show you how you can go wrong. This is something a novice won't find in many
other books. This perspective leads to another way of thinking, i.e. to not
simply follow your cheap assumptions (being a novice), but to ask yourself and
actually think about the problem instead of blaming the language for what is
usually the programmers jobs. That's something you can't learn early enough.
People tend to say C is difficult to learn. Why? Because they go wrong on so
many corner. Why? Perhaps they have the wrong mind setting. That's why these
books are good. They give you the right perspective, not only for C and C++,
but in general.
 
Define 'beginner friendly'. ;) Yes, the C version integrates into the C++
version quite nicely, which is, in this case, very good. Both books are
technically very sound. One of the key-features of these books is that they
show you how you can go wrong. This is something a novice won't find in many
other books. This perspective leads to another way of thinking, i.e. to not
simply follow your cheap assumptions (being a novice), but to ask yourself and
actually think about the problem instead of blaming the language for what is
usually the programmers jobs. That's something you can't learn early enough.
People tend to say C is difficult to learn. Why? Because they go wrong on so
many corner. Why? Perhaps they have the wrong mind setting. That's why these
books are good. They give you the right perspective, not only for C and C++,
but in general.

Well if you want to start with C++ without prior knowledge of any other coding language you probably will have a hard time following especially at the beginning and the references to C. The books often feel like a dictionaries for C/C++ and the corresponding examples look forced and sometimes it seems a bit "dry". I miss a red line going from the start to the end. If you work through the book from start to finish you probably know a lot about the language but I am not sure if you could write a decent piece of code by yourself.

However in real life as an addition to a lecture (he doesn't teach anymore if I remember correctly) the book is rather good - I should know otherwise I wouldn't have passed the exams from Klaus Schmaranz...
 

missile

Member
Well if you want to start with C++ without prior knowledge of any other coding language you probably will have a hard time following ...
Indeed. But he stated this explicitly within the first chapter, first
paragraph, second sentence; "Dieses Buch richtet sich an alle, die gerne die
Programmiersprache C++ von Grund auf erlernen wollen oder ihre Kenntnisse
vertiefen wollen. Es wird hierbei ein gewisses Grundverständnis für die
Softwareentwicklung im Allgemeinen vorausgesetzt
. ..."
. Hence, this is an
assumed prerequisite one should have.

... The books often feel like a dictionaries for C/C++ and the corresponding examples look forced and sometimes it seems a bit "dry". I miss a red line going from the start to the end. If you work through the book from start to finish you probably know a lot about the language but I am not sure if you could write a decent piece of code by yourself.
The book is about the language itself and as such the examples are more
chosen for understanding the language's foundation. Granted, it is not the
kind book teaching one how to fit elephants into a hierarchy. This was never
the assumption so to speak ... as the first sentence of this book clearly says.

About not being sure whether one is able to write a decent piece of code after
reading both books. I assume the opposite.

Well, I understand what you are saying. And for sure there are many other ways
to learn C or C++. No question about it. I just wanted to make people aware
of these two books, for those who follow a more technical understanding, for
those you wanna learn both languages from the getgo. According to my standard,
Mr. Schmaranz did a pretty good job. He explains the language rightfully while
not throwing millions of useless code listings after you.

... However in real life as an addition to a lecture (he doesn't teach anymore if I remember correctly) the book is rather good - I should know otherwise I wouldn't have passed the exams from Klaus Schmaranz...
Graz?
 

Leucrota

Member
Hey GAF,

Just started an intro to advanced programming class. We are learning C++ by comparing it to Java which is what we learned to Intro.

I want to do some programming outside of class and when the labs are closed. I downloaded Notepad++ but I do not know how to compile programs which I write up in the editor.

Can somebody give me step-by-step instructions on how to do so, including other programs I may need to download?

Thanks to whomever helps.

PS we access a Linux Enterprise server in class, open and search directories and apps using the terminal, and write up the code in g++ and use the terminal to run it.

EDIT: My program is called InfiniteSeriesPi.cpp if that helps in explaining how to do it to me.
 

IceCold

Member
Best ide for C++ is Visual Studios. But you have to pay for it. Visual C++ is free though. You could use netbeans or eclipse C++ as well.
 

Leucrota

Member
Best ide for C++ is Visual Studios. But you have to pay for it. Visual C++ is free though. You could use netbeans or eclipse C++ as well.

Eh, IDEs are way more complicated than what I really need. :( I may download Eclipse, since that is what I used for Java, but I would like to learn how to compile something written in N++ either way.
 

Leucrota

Member
Why not use Visual Studio C++ Express?

http://www.microsoft.com/visualstudio/eng/downloads#d-2010-express

EDIT: Didn't see your reply.

I downloaded that and could not figure out how to use it either...

Went to Visual Studio C++ Express again. Did this:

New Project >> Empty Project

Then added a new file under Source Files by copy-pasting the code I wrote in N++. It ran by then the windowed closed before I could see the solution. How do I keep it up?
 
I downloaded that and could not figure out how to use it either...

Went to Visual Studio C++ Express again. Did this:

New Project >> Empty Project

Then added a new file under Source Files by copy-pasting the code I wrote in N++. It ran by then the windowed closed before I could see the solution. How do I keep it up?
I don't do C or C++ but try 'X = input(' Press any key to finish'); at the end, or something like os.pause
 
Maybe this can clear up some of the confusion it helped my understand why it was useful to use an interface.
http://en.wikipedia.org/wiki/Strategy_pattern
Thanks but I didn't really find it helpful.

I have another question. What is the difference or the point of "string" and new String("string");? I don't think this is exclusive to Java as JavaScript support the syntax.

Are there a special cases when it is appropriate to use new String("string"); in place of "string"?

As far as I know, they are both the same thing and you can manipulate them in the same way.
 

Axalon

Member
Thanks but I didn't really find it helpful.

I have another question. What is the difference or the point of "string" and new String("string");? I don't think this is exclusive to Java as JavaScript support the syntax.

Are there a special cases when it is appropriate to use new String("string"); in place of "string"?

As far as I know, they are both the same thing and you can manipulate them in the same way.

Technically, in Java, doing something like

String s = "blah"

Is simply setting the reference for s to some String object in the heap equal to "blah", whereas calling new String("blah") instantiates a new String object. The practical difference is that if you set multiple string variables equal to a specific string, they'll all point to the same instance in the heap. For example,

String s = "blah";
String t = "blah";

if(s == t) System.out.println("Same");
else System.out.println("Different");

would print out "Same", whereas


String s = new String("blah");
String t = new String("blah");

if(s == t) System.out.println("Same");
else System.out.println("Different");

would print out "Different".

As an aside, since strings are immutable in Java, you shouldn't ever use new String() anyway, since it's a waste of time and memory. Really, concatenating strings is horrible, since you're instantiating a bunch of new strings in the process, which will just sit in memory until the garbage collector gets around to cleaning up. For example,

String s = "The";
String name = "Larry";
s += " " + "dog" + " " + "was named" + " " + name;

causes the strings "The", "Larry", " ", "The ", "dog", "The dog", "The dog ", "was named", "The dog was named", "The dog was named ", and "The dog was named Larry" to now be sitting around in memory, when all you want is the last one. This is why the StringBuilder class exists. Learn it, love it.
 

Leucrota

Member
I don't do C or C++ but try 'X = input(' Press any key to finish'); at the end, or something like os.pause

I did something like that and it still closed. The black window with white text which popped up closed and didnt ask for input.

Here is what my screen looks like, if anyone can visually tell me what to do: LINK
 

Haly

One day I realized that sadness is just another word for not enough coffee.
"I did something like that and it still closed. The black window with white text which popped up closed and didnt ask for input.

Here is what my screen looks like, if anyone can visually tell me what to do: LINK"

Add:

"int dummy;
cin >> dummy;"

Should do the trick.
 

KorrZ

Member
I did something like that and it still closed. The black window with white text which popped up closed and didnt ask for input.

Here is what my screen looks like, if anyone can visually tell me what to do: LINK


You can add two cin.get(); 's to the end of your program, it will then stay open until you press enter.
 

Leucrota

Member
"I did something like that and it still closed. The black window with white text which popped up closed and didnt ask for input.

Here is what my screen looks like, if anyone can visually tell me what to do: LINK"

Add:

"int dummy;
cin >> dummy;"

Should do the trick.

Thanks, I did that once and it worked. Then, I tried to run it again and the window wouldnt come up again due to some error.
 
I did something like that and it still closed. The black window with white text which popped up closed and didnt ask for input.

Here is what my screen looks like, if anyone can visually tell me what to do: LINK

Visual Studio: Try running it with STRG-F5

As for the VS versions - students get them for free via Dreamspark.
 

nOoblet16

Member
Can anyone help me with this ?

I want to write a generic method in java that takes a queue of queues (i.e., the parameter is of type Queue<Queue<E>> so that every element in the queue is itself a queue), and returns a queue containing the
first elements from each queue in the given queue (so that all elements in the returned
queue belong to the generic class E). The first element in the result queue should be
the first element of the first queue; the second element should be the first element of
the second queue; and so on.


I am mostly clueless about generics but I can implement a simple queue in generic using linked lists like this

Code:
class Queue<E> {
   private LinkedList<E> items = new LinkedList<E>();
   public void enqueue(E item) {
      items.addLast(item);
   }
   public E dequeue() {
      return items.removeFirst();
   }
   public boolean isEmpty() {
      return (items.size() == 0);
   }
}

But what do I need to do for a queue within a queue ?
 

Aeris130

Member
"Queue<E>" isn't enough since work is being done onto E in your Queue class (the first element is retrieved from E and put into a new queue that'll be returned). E (something that returns the first element, much like your implementation) has to extend some sort of interface that gives the Queue<E> implementation access to a method that lets you retrieve the first element in E.

Assuming E should always be a queue (making the implementation a queue of queues), making sure E implements the Queue interface should be enough.

Code:
/**
* A class that specifies that E is something that implements the Queue interface, and that this
* class (MyQueue) behaves like a queue of items of type E.
*/
class MyQueue<E extends Queue<?>> implements Queue<E> {}

...

MyQueue<AbstractQueue<String>> var = new MyQueue<>(); // Here's a queue that consists of AbstractQueues that store String objects.

A new queue is then returned by going over each MyQueue in the list, and calling peek/poll (as specified in the interface) on it, and adding it to the queue that should be returned.

*Edit Wait, if you only need to make a method without making your own queue, just use the existing ones:

Code:
public class ClassThatHostsMethod<E> {
	
	public Queue<E> theMethod(Queue<Queue<E>> queueCeption) {
		Queue<E> result = new LinkedList<>(); // Queue is now the standard util interface, not your implementation.
		
		while (!queueCeption.isEmpty()) {
			Queue<E> var = queueCeption.poll();
			
			if (!var.isEmpty()) {
				result.add(var.poll());
			}
		}
		
		return result;
	}
}
 

nOoblet16

Member
*Edit Wait, if you only need to make a method without making your own queue, just use the existing ones:

Code:
public class ClassThatHostsMethod<E> {
	
	public Queue<E> theMethod(Queue<Queue<E>> queueCeption) {
		Queue<E> result = new LinkedList<>(); // Queue is now the standard util interface, not your implementation.
		
		while (!queueCeption.isEmpty()) {
			Queue<E> var = queueCeption.poll();
			
			if (!var.isEmpty()) {
				result.add(var.poll());
			}
		}
		
		return result;
	}
}

Yup this is it...only need to make a method...goodness gracious I should spend more time practicing programming.
Thanks a ton man !
 
Technically, in Java, doing something like

String s = "blah"

Is simply setting the reference for s to some String object in the heap equal to "blah", whereas calling new String("blah") instantiates a new String object. The practical difference is that if you set multiple string variables equal to a specific string, they'll all point to the same instance in the heap. For example,

String s = "blah";
String t = "blah";

if(s == t) System.out.println("Same");
else System.out.println("Different");

would print out "Same", whereas


String s = new String("blah");
String t = new String("blah");

if(s == t) System.out.println("Same");
else System.out.println("Different");

would print out "Different".

As an aside, since strings are immutable in Java, you shouldn't ever use new String() anyway, since it's a waste of time and memory. Really, concatenating strings is horrible, since you're instantiating a bunch of new strings in the process, which will just sit in memory until the garbage collector gets around to cleaning up. For example,

String s = "The";
String name = "Larry";
s += " " + "dog" + " " + "was named" + " " + name;

causes the strings "The", "Larry", " ", "The ", "dog", "The dog", "The dog ", "was named", "The dog was named", "The dog was named ", and "The dog was named Larry" to now be sitting around in memory, when all you want is the last one. This is why the StringBuilder class exists. Learn it, love it.

Thank you! I need to read up about stack and heap as I have forgotten about them. Could you answer my other question? It has been bugging me for a while. Your example is very clear and straightforward.
 
Java Question.

The use of abstract and interface classes. I can understand the distinctions between them but can't quite fathom their uses. Why would I want to define a class that is incomplete or has partial implementation but needs to be completed later in another class?

Making a class and implement everything, making it complete makes more senses to me than the aforementioned. Because I know all I have to do is use them as I wish and not think about, completing it later.

Should I want to introduce new methods, it is not a problem, I can override or make a new class inheriting or copying another class.

The idea is that the interface specifies essentially the means by which a method is called, and keeps that separate from the methods themselves. For example, I might have an interface "BlurImage", and two different implementations of that interface which I can switch between. Because the implementations (classes) share the same interface, the program doesn't care which one it's using and so requires no code modification to change between them other than changing which type of class to instantiate. eg: changing

BlurImage myBlur = new BlurImplementationA(); to: myBlur = new BlurImplementationB();

it's also the only means by which Java supports something approaching multiple inheritance. Say for instance I am working on a game, and in my game I have an abstract class Entity which all game entities inherit from. Now, some of these entities might have associated images to be drawn and some might not. I could have an AbstractDrawable inherit from Entity and have all drawables inherit from that (overriding the draw() method) - but that can get rather unwieldy and could lead to design issues down the line if I want an Entity to inherit both Drawable and some other aspect.

So instead I define an interface "drawable" and then all the Entities that I wish to have associated images can simply implement drawable.

Give this methods such as loadImage(), drawImage() and implement them however you wish in the classes. Then you could at the start of the game create a list of all your drawables and iterate through calling loadImage() etc. You might even implement it in an abstract parent or two and thus have inherited drawable implementations of several types which can all be treated the same by the program.

I understand where you're coming from and it might seem like a lot of unnecessary work but as the project gets larger (or you wish to reuse elements in other projects) interfaces are going to make your program easier to understand and, perhaps more importantly, easier to modify and reuse.
 
Java Question.

The use of abstract and interface classes. I can understand the distinctions between them but can't quite fathom their uses. Why would I want to define a class that is incomplete or has partial implementation but needs to be completed later in another class?

Making a class and implement everything, making it complete makes more senses to me than the aforementioned. Because I know all I have to do is use them as I wish and not think about, completing it later.

Should I want to introduce new methods, it is not a problem, I can override or make a new class inheriting or copying another class.

Someone earlier mentioned the Strategy Pattern as perhaps a starting off point for understanding, and patterns can indeed demonstrate effective usage of abstract classes and interfaces.

As an example, as an author of a class, you might know some generalities about how the class has to operate, but you do not have the complete picture, or there are several mutually exclusive possibilities for execution. While you might consider putting an if/else or some other logical structure in your code, it can grow as requirements change and become unwieldy. Another option is to punt. Define a base abstract class, fill in as many details as you can, and provide abstract methods for subclasses to fill in the gaps as they require them. And as requirements change, the abstract base class and existing subclasses might be protected from change, provided the change is an area already identified as volatile. Leave the existing classes alone, add another subclass. Applying this technique over an algorithm, for example, is often referred to as the Template Method Pattern.

But maybe you do not have that degree of change or volatility in your code. You might not, it might be fairly straightforward and stable, with not many repeated if/else structures or anything like that. But you can still benefit from the concept of abstract classes and, notably, interfaces. The writing of unit tests really highlights the effective use of interfaces.

You cover your code with tests, each one trying to test as small a unit of work as you can get away with, with laser-like focus on a given piece of logic. If that test should fail, you want to know precisely what did not work as expected, without having to do a lot of debugging and stepping through code line by line. It should pop out at you, preferably immediately. However, this is often hard to do. You have a lot of classes working together (if you have generally good separation of concerns) or you might have a kitchen sink procedural code method that does everything. When you write tests for that, you find it hard to arrive at the type of isolation that you desire when and if something fails. Extracting code into classes and further extracting interfaces from those classes allows you to arrive at decoupled, testable code that will let you replace functionality that is irrelevant to your test (or maybe could just slow your test down) so that you can focus on what is truly important in that particular test scenario.

A crude example, making it up on the fly. Say you have a program that calls out to a website to pull down an RSS feed, then parses that feed and stores it into a database. At a high level, you have 3 steps to this algorithm. 1) Get feed. 2) Parse. 3) Save to database. The details of each of these steps can be full of details. But at that high level, all you are maybe concerned about is that the algorithm executes. So what do you do? Maybe you express each step of the algorithm in its own class. Your method under test is simply responsible for managing its workflow.

Code:
public void LoadRSS()
{
    var feedItems = rssReader.GetItems();
    var parsedItems = rssParser.Parse(feedItems);
    db.Save(parsedItems);
}

That looks pretty simple, doesn't it? But how do you test it? Do you have to find some RSS feed that exists, verify what's there, pull that down, verify all the data gets parsed correctly, and then look in the database to make sure that everything you wanted to be there is there in the correct format? That's a pretty big test. But we stated before that all we were concerned about in this test is the execution of the algorithm. That the program read the feed, parsed the items, and saved them. The details of all those actions are irrelevant. Well, what we can do is from those classes, we extract interfaces and replace them during our tests with fakes. (And it's not that we don't care about those processes, it's just that we will write separate, isolated tests for them, as well.)

Code:
[TestMethod]
public void LoadRSS_AlgorithmExecutesSuccessfully()
{
      var reader = new FakeRssReader();
      var parser = new FakeRssParser();
      var db = new FakeDatabase(); 

      var stagedItems = new List<RssItem>();
      var stagedParsedItems = new List<RssDataItem>();

      reader.SetRssItemsToReturn(stagedItems);
      parser.SetParsedItemsToReturnForRssFeedItems(stagedItems, stagedParsedItems);
      db.SetExpectedDataItems(stagedParsedItems);

      var loader = new RssLoader(reader, parser, db);
      loader.LoadRSS();
      db.Verify();
}

With the fakes in place, it's fairly simple to test the algorithm. You expect the reader to be invoked, it will return items. You expect those items to be passed to a parser that will return other items. And you finally expect those parsed items to be sent to the database. What each of those classes are doing is not the point of your test. You just want to verify the algorithm, and you have.

What makes it work is the interfaces, and then RssLoader exposing dependencies to those interfaces in the constructor.

Code:
public interface IRssReader 
{
       IEnumerable<RssItem> GetItems();
}

public class RssReader : IRssReader
{
       public IEnumerable<RssItem> GetItems()
       {
              /* real details here */
       }
}

class FakeRssReader : IRssReader
{
       public IEnumerable<RssItem> GetItems()
       {
             /* fake details here */
       }

       // helper methods here, to assist staging data and/or setting expectations
} 

public class RssLoader
{
     IRssReader reader;
     IRssParser parser;
     IDatabase db;

     public RssLoader(IRssReader reader, IRssParser parser, IDatabase db)
     {
            this.reader = reader;
            this.parser = parser;
            this.db = db;
     }

Anyway, that's probably more info than you cared about, but given time, you will find patterns and testing will drive you to interfaces and abstract classes more than you realize.

(Code samples follow C# idioms, as an FYI.)
 
Ugh, probably LTTP here, but VS2012's new interface is a complete train wreck in every way possible.

What the hell was Microsoft thinking? Don't send your goddamn marketing department to redesign your power users UIs.

Awful.
 

CrankyJay

Banned
Ugh, probably LTTP here, but VS2012's new interface is a complete train wreck in every way possible.

What the hell was Microsoft thinking? Don't send your goddamn marketing department to redesign your power users UIs.

Awful.

Yeah, it's pretty awful. They actually made TFS integration even worse.

The only thing I like about it is the merge tool.
 
Yeah, it's pretty awful. They actually made TFS integration even worse.

The only thing I like about it is the merge tool.

Yeah, the TFS integration was actually the thing that drove me to post this. I'm still trying to figure out how to check in a certain set of changes and undo another, and I can't quite go through with it because I know something will break.

I did like the new merge tool (though I have to fix the color scheme to get the text readable in zenburn).

Actually having TFS support in the Express version is huge too. It's sad that the environment is several steps down in every other way, though.

When you look and operate worse than Eclipse, you know you screwed up.
 

CrankyJay

Banned
Yeah, the TFS integration was actually the thing that drove me to post this. I'm still trying to figure out how to check in a certain set of changes and undo another, and I can't quite go through with it because I know something will break.

I did like the new merge tool (though I have to fix the color scheme to get the text readable in zenburn).

Actually having TFS support in the Express version is huge too. It's sad that the environment is several steps down in every other way, though.

When you look and operate worse than Eclipse, you know you screwed up.

Yeah, they regressed here and the learning curve for doing what you did in 2010 is obnoxious.

You can include/exclude changes to changesets still, it's just not as easily obvious as it used to be.
 

Lonely1

Unconfirmed Member
Asking resident Haskell experts on GAF:

My problem is the following: I have a function "f" that generates sets of strings recursively which length grows exponentially. I have another function "g" that calls "f" and extracts subsets of its results according to the position of the requested elements.

My problem is the following: While calling "g" works very fast, I have been trying to calculate the lenght of "f" with lenght (f (x y) ) and it have yet to finish after 3 hours. Even if I ask "g" to compute a sublist of a "f" set with higher recursive level (which means that it needs f(x y) in order to compute its elements), "g" still yields result very fast...

Is lazy evaluation really that awezome? Because I'm getting worried that my program doesn't behaves like it should.
 

Lonely1

Unconfirmed Member
Great, now Hugs crashed and shows the following message: "Error - Garbage collection fails to reclaim sufficient space"
 

nan0

Member
Yeah, it's pretty awful. They actually made TFS integration even worse.

The only thing I like about it is the merge tool.

Why? It doesn't look too different with the "Blue" color scheme. Yeah, the all-caps menus are ugly, but you can change them.
 

CrankyJay

Banned
Why? It doesn't look too different with the "Blue" color scheme. Yeah, the all-caps menus are ugly, but you can change them.

Because they moved a bunch of menu items and button clicks that people got used to, and buried it a couple layers deep. It's stupid.
 
Top Bottom