Tannheuser
Tannheuser

Reputation: 416

Use methods in classes

I have two classes. Let them be Directory and File for example. There are my own custom classes, not a part of .NET Framework. So, Directory has Title field and list of files. File has several fields too.

Where should I place methods which will return list of files by directory title for example, in Directory class or in File class?

i.e. which of these is better:

public List<Files> Directory.GetFiles(string directoryTitle){...}
public List<Files> File.GetFilesByDirectory(string directoryTitle){...}

and why?

Upvotes: 2

Views: 94

Answers (4)

Andy Stannard
Andy Stannard

Reputation: 1703

I would personally leave both of those classes alone and create a 3rd class to do the work which maximises the opportunity for code reuse. Call it DirectoryFileFinder or something similar.

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45083

Where you actually put them is your own prerogative, but I'd say it is more semantically sound to use the first version in this instance: Directory.GetFiles. The NET framework actually exposes a Directory class which you could use as an example of this, containing such a method.

It would also seem kind of counter-intuitive doing it the other way, all else aside, considering that the directory instance already contains a list of known files.

Upvotes: 0

sll
sll

Reputation: 62504

I would say first is better

public List<Files> Directory.GetFiles(string directoryTitle){...} 

Since File itself should not be aware where it is located and Directory is aware which files it contains.

Upvotes: 0

n8wrl
n8wrl

Reputation: 19765

Two thoughts:

first, it's the Directory that knows about listing files, so that's where that should live.

Second, try to stick to interfaces for your return types - IList instead of List. That gives you more flexibility for returning different kinds of lists AND for unit testing.

Upvotes: 4

Related Questions