Lang thang
Lang thang

Reputation: 291

Is there other ways to write this code for more flexibility

Now, I have a list of 5 Students (example) in db with IDs are 1,2,3,4,5 in order.

In my code, I want to treat these students in many different ways by using different functions.

For example, Student ID 1 will be worked with the function name 'Call_History()'

Student 2 will be used for the function name 'Get_Record()'

Similar to the rest.

Here is my code:

if(studentID == 1) Call_History();
else if(studentID == 2) Get_Record();
else ....

So, with list of 10 students, I have to write code if...else 10 times. What I want to ask here is: Is there any way (except using switch) to help me write code more fexibility?

Upvotes: 1

Views: 116

Answers (4)

Devesh
Devesh

Reputation: 4550

As you need to determine the logic based on the ID of the student , you have to write the piece of the code somewhere , you can not skip it. One of the way i think is Factory pattern will also help you to make your code better and maintainable

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109557

This example is in C#, but there are similar data structures in other languages such as Java.

You could use a Dictionary<int, Action> which is initialised with all the action/ID combinations.

Then do something like:

if (actionMap.ContainsKey(studentId))
    actionMap[studentId]();

Upvotes: 2

David
David

Reputation: 16277

use dictionary

Dictionary<int, delegate> allStudentsAndActions=new (...);

allStudentsAndActions.Add(1, FirstMethod);
...
allStudentsAndActions.Add(N, OtherMethod);

Upvotes: 1

Nahum
Nahum

Reputation: 7197

use one of the following design patterns

http://en.wikipedia.org/wiki/Template_method_pattern or http://en.wikipedia.org/wiki/Strategy_pattern

Upvotes: 2

Related Questions