473,769 Members | 2,240 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initialise elsewhere -- as simple as possible...



Up until lately I've been writing all mad kinds of code for accomplishing
things, but lately I've decided to lean more toward the whole readability,
etc. side of things.

I have a command line application, which I intend to be used like so:

unicon.exe -8to32 source.txt target.txt
There are three command line arguments. The first is something like:

-8to16 or -16to8 or -8to32
The next two arguments are filenames.
I want my "main" function to be as simple as possible; I achieve this by
delegating the work to other functions. Here's how it looks so far:
struct CmdLineInfo
{
class Bad_Option {};

enum ConversionType { EightToSixteen, EightToThirtytw o,
SixteenToEight, SixteenToThirty two,
ThirtytwoToEigh t, ThirtytwoToSixt een };

ConversionType conversion;
const char* source;
const char* target;

CmdLineInfo( ConversionType const a, const char* const b, const char*
const c )
: conversion(a), source(b), target(c) {}
};
CmdLineInfo GetCmdLineInfo( int argc, char * argv[] );
//This function analyses the arguments and returns a structure
//by value.
//If the first argument is invalid, it throws an exception
//of type, "Excp_EndPr og".
int main(int argc, char* argv[])
{
try
{
CmdLineInfo const &cmdline_inf o = GetCmdLineInfo( argc, argv);
}
catch(Excp_EndP rog e)
{
return e.code;
}
}

Next thing I want to do is open the two files, but again, I want to delegate
this work. I shall be using objects of the type "fstream". Here's how I
would like my code to look:

int main(int argc, char* argv[])
{
try
{
CmdLineInfo const &cmdline_inf o = GetCmdLineInfo( argc, argv);

ifstream& source = OpenSourceFile( argv[1] );

ofstream& target = OpenTargetFile( argv[2] );

//Now proceed to manipulate the files
}
catch(Excp_EndP rog e)
{
return e.code;
}
}
If either "OpenSourceFile " or "OpenTargetFile " fail to open the files
successfully, I'll make them throw an exception.

The problem with the code above is that, for the "OpenSourceFile " function
to be able to initialise the "ifstream" object, the "ifstream" object
_can't_ be a local variable of main (which is what I want).
I know I can dynamically allocate it in "OpenSourceFile ", and even use an
auto_pointer, or I could even use "placement new", but is there not a nice
clean way to do it.

Here's the general idea:

class SomeType
{
public:

int k;

SomeType( int const a ) : k(a) {}
};
SomeType& OtherFunction()
{
//In here we initialise the object
}
int main()
{
SomeType k; //But somehow don't initalise it.

k = Otherfunction() ;
}
See what I'm trying to do?
-Tomás
Mar 31 '06 #1
2 1764
Tomás wrote:
[snippers]
int main(int argc, char* argv[])
{
try
{
CmdLineInfo const &cmdline_inf o = GetCmdLineInfo( argc, argv);

ifstream& source = OpenSourceFile( argv[1] );

ofstream& target = OpenTargetFile( argv[2] );

//Now proceed to manipulate the files
}
catch(Excp_EndP rog e)
{
return e.code;
}
}
If either "OpenSourceFile " or "OpenTargetFile " fail to open the files
successfully, I'll make them throw an exception.

The problem with the code above is that, for the "OpenSourceFile " function
to be able to initialise the "ifstream" object, the "ifstream" object
_can't_ be a local variable of main (which is what I want).


Why can't it be local to main? Really delegate.

Here come some fragments.

class SourceData
{
public:
// yada yada ctor, dtor, copy ctor, op=, etc.
// the ctor includes closing the file in a tidy manner
int StartFile(std:: string name);
private:
ifstream& source;
};

Then add the stuff you need to do to this file. Keep in mind the
notion
that one day you may not be fetching a disc file, but from a URL, or
from some network virtual connection, or SQL calls from a database,
or any old thing you could think of.

Here comes some more fragments. I'm typing this in at the terminal,
so things may not be syntactically correct.

int main(int argc, char* argv[])
{
try
{
CmdLineInfo const cmdline_info(ar gc,argv);

// someplace here you need to define input and
// output mode information, maybe it's done in CmdLineInfo
// maybe that's the 8to32 things, and maybe inMode and outMode
// are really calls to cmndline_info

SourceData mySource(cmdlin e_info.GetSourc eName(), inMode);
DestData myDest(cmdline_ info.GetDestNam e(), outMode);

// the ctor is where you put all the work of getting the file ready
// to start reading/writing

// Notice I said source and dest, not file names

//Now proceed to manipulate the data
mySource.Prepar eToReadLines();
myDest.PrepareT oWriteLines();
while(mySource. Done() != TRUE)
{
myDest.WriteOne Line(mySource.R eadOneLine());
}
}
catch(Excp_EndP rog e)
{
return e.code;
}
}

Really delegate. Don't just use a class as a thing to hold stuff in.
Make it do the work.

Or maybe you need to read in the entire input file into some data
structure.

class Splorp8to32
{
// yada yada ctor dtor op= etc.
};

(Because you mentioned 8to32 and like in your post.)

Then you can do this in a few ways. But what you
want is for the internal data structure not to know about the
details of the file it was stored in. So you want to be able
to build up a Splorp from some kind of thing you can pull
from the file. Line by line, or groupings, or whatever.
So you put a "get one line" func in your input file class.
And you put an "accept one line to add to the Splorp"
func in your Splorp class.

Splorp32 mySplorp;
mySplorp.Prepar eToAcceptLines( );
while(mySource. Done() != TRUE)
{
mySplorp.Accept OneLine(mySourc e.ReadOneLine() );
}

And for writing it out, you just go in the other direction.
You put a "proffer up one line worth of the Splorp" in
your Splorp class, and a "write one line" func in
your output class.

Or you divide it into groups or icons or sprites or
whatever works for Splorps. And your input and output
file classes know how to get one of these chunks into
or out of the storage file. For example, it might be database
calls, and your input/output classes might have to do some
SQL calls to get/retrieve one chunk. But Splorp never gets
to see any of that.

And so on. Really delegate.

Then you can get as magnificently fancy, or as simple, as
your app requires. For example: You could buffer the read/write
ops, so the next, previous, and current line are available. Or
you could log all reads/writes and allow backup/restore.
Or you could add security to every step. Or CRC checks in
case the data line is suspect. And all that junk is going to
be hidden.
Socks

Mar 31 '06 #2
In article <t_************ ******@news.ind igo.ie>,
"Tomás" <NU**@NULL.NULL > wrote:
Up until lately I've been writing all mad kinds of code for accomplishing
things, but lately I've decided to lean more toward the whole readability,
etc. side of things.

I have a command line application, which I intend to be used like so:

unicon.exe -8to32 source.txt target.txt
There are three command line arguments. The first is something like:

-8to16 or -16to8 or -8to32
The next two arguments are filenames.
I want my "main" function to be as simple as possible; I achieve this by
delegating the work to other functions. Here's how it looks so far:
struct CmdLineInfo
{
class Bad_Option {};

enum ConversionType { EightToSixteen, EightToThirtytw o,
SixteenToEight, SixteenToThirty two,
ThirtytwoToEigh t, ThirtytwoToSixt een };

ConversionType conversion;
const char* source;
const char* target;

CmdLineInfo( ConversionType const a, const char* const b, const char*
const c )
: conversion(a), source(b), target(c) {}
};
CmdLineInfo GetCmdLineInfo( int argc, char * argv[] );
//This function analyses the arguments and returns a structure
//by value.
//If the first argument is invalid, it throws an exception
//of type, "Excp_EndPr og".
int main(int argc, char* argv[])
{
try
{
CmdLineInfo const &cmdline_inf o = GetCmdLineInfo( argc, argv);
}
catch(Excp_EndP rog e)
{
return e.code;
}
}

Next thing I want to do is open the two files, but again, I want to delegate
this work. I shall be using objects of the type "fstream". Here's how I
would like my code to look:

int main(int argc, char* argv[])
{
try
{
CmdLineInfo const &cmdline_inf o = GetCmdLineInfo( argc, argv);

ifstream& source = OpenSourceFile( argv[1] );

ofstream& target = OpenTargetFile( argv[2] );

//Now proceed to manipulate the files
}
catch(Excp_EndP rog e)
{
return e.code;
}
}
If either "OpenSourceFile " or "OpenTargetFile " fail to open the files
successfully, I'll make them throw an exception.

The problem with the code above is that, for the "OpenSourceFile " function
to be able to initialise the "ifstream" object, the "ifstream" object
_can't_ be a local variable of main (which is what I want).
I know I can dynamically allocate it in "OpenSourceFile ", and even use an
auto_pointer, or I could even use "placement new", but is there not a nice
clean way to do it.

Here's the general idea:

class SomeType
{
public:

int k;

SomeType( int const a ) : k(a) {}
};
SomeType& OtherFunction()
{
//In here we initialise the object
}
int main()
{
SomeType k; //But somehow don't initalise it.

k = Otherfunction() ;
}
See what I'm trying to do?


I would open the files in main, then pass them to other function(s) that
do the parsing.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 31 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2074
by: Jerry Sievers | last post by:
Greetings. On Python 2.3.3, is there any way to have the .pyc files created elsewhere than in the same dir as the source files? I have an application that consists of about 30 source files including a few packages. I would like it if my .pyc files could be in a subdir of the app root if possible. I would have to make sure that the subdir structure
2
2808
by: sam | last post by:
Hi, Can anyone tell me how to initialise list<HashMap> in STL? I written the following function, but if the "key" is not in the hash table, the return value causes: "terminate called after throwing an instance of 'std::length_error' what(): vector::reserve Abort (core dumped) "
9
2526
by: iceColdFire | last post by:
HI, I have a function as void f(int p) { return p++; } now I have created a function pointer as
6
5436
by: Stuart Norris | last post by:
Dear Readers, I am attempting to initialise a struct contiaing a dynamic character string. In the example below I am trying to initialise the name field so that my struct does not waste space. I know if I change char name this will work, but I will waste alot of space. (I am learning so I want to learn the best way) How can I define a struct the allows variable length character strings in the
3
1097
by: Annie | last post by:
hello all, is it possible at all? i have a class that encapsulates a Hashtable collection. What i want is to initialise this object once and only once and then be able to access its Public Static methods always. What i want is when the user logs in i gets its detail and add him/her in the hashtable until her/she is online and similarly
2
7211
by: Charles Law | last post by:
Does anyone know if it is possible to initialise a structure array at run-time, something like this: <code> Structure struct Dim a As String Dim b As Integer Dim c As End Structure
14
1829
by: Frederick Gotham | last post by:
How do we initialise an aggregate member object of a class? The following won't compile for me: struct MyStruct { int i; double d; }; class MyClass { private:
5
3744
by: Owen Ransen | last post by:
When I installed the new VC 2005 I though, aha at last I will be able initialise static const members in the H file, and I can, but only integer types. double types have to be declared in the H file but initialied in the CPP file. It seems that MS is following the standard this time, but why is there that rule?
4
2292
by: =?Utf-8?B?Qm9uaQ==?= | last post by:
Hi, I got this problem. I'm implementing a pluggable winform program. My plugins are usercontrol and I load them in my program through a interface. Now if I close my application an error occurs: "Object is currently in use elsewhere". If I comment the line where a I use the Activator.CreateInstance it doesn't happen. I tried to disposed the object created but nothing but If I do a simple new of my object without using reflection it...
0
10223
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.